#include "piqt_highlighter.h"


ConfigHighlighter::ConfigHighlighter(QTextDocument * parent): QSyntaxHighlighter(parent) {
	HighlightingRule rule;

	valueNameFormat.setForeground(QColor(0, 64, 154));
	rule.pattern = QRegularExpression("[^=]"); //"\\b[A-Za-z0-9_]+(?=\\()");
	rule.format  = valueNameFormat;
	highlightingRules.append(rule);

	valueFormat.setForeground(QColor(192, 0, 0));
	rule.pattern = QRegularExpression("=[^\n]*");
	rule.format  = valueFormat;
	highlightingRules.append(rule);

	equalFormat.setFontWeight(QFont::Bold);
	equalFormat.setForeground(QColor(96, 126, 0));
	rule.pattern = QRegularExpression("=");
	rule.format  = equalFormat;
	highlightingRules.append(rule);

	sectionFormat.setFontWeight(QFont::Bold);
	sectionFormat.setForeground(QColor(0, 32, 64));
	rule.pattern = QRegularExpression("\\[.*\\]");
	rule.format  = sectionFormat;
	highlightingRules.append(rule);

	substFormat.setForeground(QColor(192, 0, 192));
	rule.pattern = QRegularExpression("\\$\\{.*\\}+");
	// rule.pattern.setMinimal(true);
	rule.format  = substFormat;
	highlightingRules.append(rule);
	rule.pattern = QRegularExpression("\\$\\{[^\\{]*\\}+");
	highlightingRules.append(rule);

	singleLineCommentFormat.setFontItalic(true);
	singleLineCommentFormat.setForeground(QColor(128, 128, 128));
	rule.pattern = QRegularExpression("#[^\n]*");
	rule.format  = singleLineCommentFormat;
	highlightingRules.append(rule);

	spaceFormat.setForeground(QColor(210, 210, 210));

	// commentStartExpression = QRegExp("/\\*");
	// commentEndExpression = QRegExp("\\*/");
}


void ConfigHighlighter::highlightBlock(const QString & text) {
	foreach(const HighlightingRule & rule, highlightingRules) {
		QRegularExpression expression(rule.pattern);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
		QRegularExpressionMatchIterator i = expression.globalMatch(text);
		while (i.hasNext()) {
			QRegularExpressionMatch match = i.next();
			setFormat(match.capturedStart(), match.capturedLength(), rule.format);
		}
#else
		int index = expression.indexIn(text);
		while (index >= 0) {
			int length = expression.matchedLength();
			setFormat(index, length, rule.format);
			index = expression.indexIn(text, index + length);
		}
#endif
	}
	setCurrentBlockState(0);

	QRegularExpression expression("[ |\t]");
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
	QRegularExpressionMatchIterator i = expression.globalMatch(text);
	while (i.hasNext()) {
		QRegularExpressionMatch match = i.next();
		setFormat(match.capturedStart(), match.capturedLength(), spaceFormat);
	}
#else
	int index = expression.indexIn(text);
	while (index >= 0) {
		int length = expression.matchedLength();
		setFormat(index, length, spaceFormat);
		index = expression.indexIn(text, index + length);
	}
#endif
}
