#include "FormatToStream.h"
#include <QRegularExpression>
#include <QTextStream>

void FormatToStream(QTextStream &stream, QString format, std::function<void(QTextStream &, QString)> field_callback)
{
	// Use static to optimize only once
    static QRegularExpression cached_find_var_re("(?:[^\\\\]|^)(\\/%([a-zA-Z0-9_-]+)%\\/)");

	int from = 0;
	QRegularExpressionMatch match;
	while (format.indexOf(cached_find_var_re, from, &match) >= 0) {
		if (from > 0) {
			// Because the regex has to check for backslash in front we have the from position
			// one position before where we actually should continue for the second match and later ie when from > 0
			// Therefor increase from by 1 to make the substring (midRef) calculation work
			++from;
		}
		// copy code before the var to the stream
        stream << format.mid(from, match.capturedStart(1) - from);
		field_callback(stream, match.captured(2));
		from = match.capturedEnd()-1; // -1 because it wants to match one character before or start of line to make sure there is no backslash
	}
	if (from > 0) {
		// same reason as at the start of the loop
		++from;
	}
    stream << format.mid(from);
}
