#include "widgets.h"

#include <QKeyEvent>


namespace Dict {

Search::Search(Browser *parent)
	: QWidget(parent), browser(parent), found(false)
{
	setupUi(this);

	button->setIcon(QIcon::fromTheme("dialog-close"));
	nextMatch->setIcon(QIcon::fromTheme("go-down-search"));
	prevMatch->setIcon(QIcon::fromTheme("go-up-search"));

	connect(pattern, SIGNAL(textChanged(const QString &)),
		SLOT(search(const QString &)));
	connect(nextMatch, SIGNAL(pressed()), SLOT(next()));
	connect(prevMatch, SIGNAL(pressed()), SLOT(prev()));
	connect(hilite, SIGNAL(toggled(bool)), SLOT(hiliteAll(bool)));

	layout()->setAlignment(Qt::AlignLeft);
	layout()->setContentsMargins(4, 0, 4, 0);
	setFocusProxy(pattern);
	QWidget::hide();
}

void Search::show()
{
	QWidget::show();
	setFocus();
	pattern->selectAll();
}

void Search::hide()
{
	browser->setFocus();
	QWidget::hide();
}

void Search::find(QTextDocument::FindFlags backward)
{
	if (!found) {
		if (!isVisible()) show();
		search(pattern->text());
		return;
	}
	browser->savePosition();
	if (backward && browser->textCursor().atStart())
		browser->moveCursor(QTextCursor::End);

	if (browser->find(pattern->text(), backward))
		message->setText(i18n("Text found"));
	else {
		browser->clearSelection();
		browser->moveCursor(QTextCursor::Start);
		browser->restorePosition();
		message->setText(i18n("No more matches"));
	}
}

void Search::search(const QString &text)
{
	browser->savePosition();

	bool empty = text.isEmpty();
	nextMatch->setEnabled(!empty);
	prevMatch->setEnabled(!empty);

	if (empty) {
		browser->clearSelection();
		browser->restorePosition();
		clear();
		return;
	}
	browser->moveCursor(QTextCursor::Start);
	if ((found = browser->find(text))) {
		message->setText(i18n("Text found"));
	} else {
		browser->restorePosition();
		message->setText(i18n("Text not found"));
	}
}

void Search::clear()
{
	if (!isVisible())
		pattern->clear();
	message->clear();
	found = false;
}

void Search::keyPressEvent(QKeyEvent *event)
{
	if (event->key() == Qt::Key_Escape)
		hide();
	else
		browser->keyPressEvent(event);
}

void Search::hiliteAll(bool hilite)
{
	Hiliter *hiliter = browser->textHiliter();
	if (hilite) {
		hiliter->setText(pattern->text());
		connect(pattern, SIGNAL(textChanged(const QString &)),
			hiliter, SLOT(setText(const QString &)));
	} else {
		hiliter->setText("");
		pattern->disconnect(hiliter);
	}
}

}
