/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "textsearchhandler.h"
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <QtDebug>
#include "interfaces/monocle/isearchabledocument.h"
#include "pagegraphicsitem.h"
#include "pageslayoutmanager.h"

namespace LeechCraft
{
namespace Monocle
{
	TextSearchHandler::TextSearchHandler (QGraphicsView *view, PagesLayoutManager *mgr, QObject *parent)
	: QObject (parent)
	, View_ (view)
	, Scene_ (view->scene ())
	, LayoutMgr_ (mgr)
	, CurrentRectIndex_ (-1)
	{
	}

	void TextSearchHandler::HandleDoc (IDocument_ptr doc, const QList<PageGraphicsItem*>& pages)
	{
		Doc_ = doc;
		Pages_ = pages;

		CurrentHighlights_.clear ();
		CurrentRectIndex_ = -1;
		CurrentSearchString_.clear ();
	}

	bool TextSearchHandler::Search (const QString& text, Util::FindNotification::FindFlags flags)
	{
		if (!Doc_)
			return false;

		if (text != CurrentSearchString_)
		{
			CurrentSearchString_ = text;
			for (auto item : CurrentHighlights_)
			{
				auto parentPage = static_cast<PageGraphicsItem*> (item->parentItem ());
				parentPage->UnregisterChildRect (item);
				Scene_->removeItem (item);
				delete item;
			}

			CurrentHighlights_.clear ();

			auto searchable = qobject_cast<ISearchableDocument*> (Doc_->GetQObject ());
			if (!searchable)
				return false;

			const QBrush brush (Qt::yellow);

			auto cs = flags & Util::FindNotification::FindCaseSensitively ?
					Qt::CaseSensitive :
					Qt::CaseInsensitive;
			const auto& map = searchable->GetTextPositions (text, cs);
			for (auto i = map.begin (); i != map.end (); ++i)
			{
				auto page = Pages_.at (i.key ());
				for (const auto& rect : *i)
				{
					auto item = new QGraphicsRectItem (page);
					item->setBrush (brush);
					item->setZValue (1);
					item->setOpacity (0.2);
					CurrentHighlights_ << item;

					page->RegisterChildRect (item, rect,
							[item] (const QRectF& rect) { item->setRect (rect); });
				}
			}

			if (!CurrentHighlights_.isEmpty ())
				SelectItem (0);

			return !CurrentHighlights_.isEmpty ();
		}

		if (CurrentHighlights_.isEmpty ())
			return false;

		if (flags & Util::FindNotification::FindBackwards)
		{
			auto nextIdx = CurrentRectIndex_ - 1;
			if (nextIdx < 0)
			{
				if (flags & Util::FindNotification::FindWrapsAround)
					nextIdx = CurrentHighlights_.size () - 1;
				else
					return false;
			}
			SelectItem (nextIdx);
		}
		else
		{
			auto nextIdx = CurrentRectIndex_ + 1;
			if (nextIdx >= CurrentHighlights_.size ())
			{
				if (flags & Util::FindNotification::FindWrapsAround)
					nextIdx = 0;
				else
					return false;
			}
			SelectItem (nextIdx);
		}

		return true;
	}

	void TextSearchHandler::SelectItem (int index)
	{
		if (CurrentRectIndex_ >= 0 && CurrentRectIndex_ < CurrentHighlights_.size ())
		{
			auto oldHili = CurrentHighlights_.at (CurrentRectIndex_);
			oldHili->setOpacity (0.2);
			oldHili->setPen (QPen ());
		}

		auto item = CurrentHighlights_.at (index);
		item->setOpacity (0.6);
		item->setPen ({ Qt::black });
		CurrentRectIndex_ = index;

		auto pageItem = static_cast<PageGraphicsItem*> (item->parentItem ());
		const auto pageIdx = LayoutMgr_->GetPages ().indexOf (pageItem);
		if (pageIdx >= 0)
		{
			const auto& bounding = pageItem->boundingRect ();
			const auto x = item->rect ().x () / bounding.width ();
			const auto y = item->rect ().y () / bounding.height ();
			emit navigateRequested ({}, pageIdx, x, y);
		}
	}
}
}
