#include "hiliter.h"

#include <QTextCharFormat>


namespace Dict {

Hiliter::Hiliter(QObject *parent)
	: QSyntaxHighlighter(parent)
{
	hilites.resize(2);

	QTextCharFormat format;
	format.setBackground(Qt::yellow);
	setHiliteFormat(format, Text);

	hilites[Text].regexp = QRegExp("", Qt::CaseInsensitive, QRegExp::FixedString);
	hilites[Query].regexp = QRegExp("", Qt::CaseInsensitive);
}

void Hiliter::setText(const QString &text)
{
	hilites[Text].regexp.setPattern(text);
	rehighlight();
}

void Hiliter::setQuery(const QString &text)
{
	QString pattern = "\\b" + text;
	hilites[Query].regexp.setPattern((text.size()) ? pattern : "");
	rehighlight();
}

void Hiliter::setHiliteFormat(QTextCharFormat format, HiliteType hilite)
{
	hilites[hilite].format = format;
}

void Hiliter::highlightBlock(const QString &text)
{
	foreach (const Hilite &hilite, hilites) {
		const QRegExp &exp = hilite.regexp;
		if (exp.pattern().isEmpty()) continue;
		int index = exp.indexIn(text);
		while (index >= 0) {
			int len = exp.matchedLength();
			if (len <= 0) break;
			setFormat(index, len, hilite.format);
			index = exp.indexIn(text, index + len);
		}
	}
}

}
