/**********************************************************************
 * 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 "quarkorderview.h"

#if QT_VERSION < 0x050000
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QGraphicsObject>
#else
#include <QQmlContext>
#include <QQmlEngine>
#include <QQuickItem>
#endif

#include <QtDebug>
#include <util/gui/unhoverdeletemixin.h>
#include <util/sys/paths.h>
#include <util/qml/colorthemeproxy.h>
#include <util/qml/themeimageprovider.h>
#include <util/qml/unhidelistmodel.h>
#include <util/util.h>
#include "viewmanager.h"
#include "quarkmanager.h"

namespace LeechCraft
{
namespace SB2
{
	QuarkOrderView::QuarkOrderView (ViewManager *manager, ICoreProxy_ptr proxy, QWidget *parent)
#if QT_VERSION < 0x050000
	: QDeclarativeView (parent)
#else
	: QQuickView (parent->windowHandle ())
#endif
	, Manager_ (manager)
	, Proxy_ (proxy)
	, Model_ (new Util::UnhideListModel (this))
	{
		new Util::UnhoverDeleteMixin (this);

		const auto& file = Util::GetSysPath (Util::SysPath::QML, "sb2", "QuarkOrderView.qml");
		if (file.isEmpty ())
		{
			qWarning () << Q_FUNC_INFO
					<< "file not found";
			deleteLater ();
			return;
		}

		const auto& quarks = manager->GetAddedQuarks ();
		if (quarks.isEmpty ())
		{
			deleteLater ();
			return;
		}

		for (const auto& quark : quarks)
		{
			auto quarkMgr = manager->GetAddedQuarkManager (quark);
			auto item = new QStandardItem;

			const auto& manifest = quarkMgr->GetManifest ();

			item->setData (manifest.GetName (), Util::UnhideListModel::Roles::ItemName);
			item->setData (manifest.GetDescription (), Util::UnhideListModel::Roles::ItemDescription);
			item->setData (manifest.GetID (), Util::UnhideListModel::Roles::ItemClass);
			item->setData (Util::GetAsBase64Src (manifest.GetIcon ().pixmap (32, 32).toImage ()),
					Util::UnhideListModel::Roles::ItemIcon);
			Model_->appendRow (item);
		}

#if QT_VERSION < 0x050000
		setStyleSheet ("background: transparent");
		setWindowFlags (Qt::ToolTip);
		setAttribute (Qt::WA_TranslucentBackground);
#endif

		for (const auto& cand : Util::GetPathCandidates (Util::SysPath::QML, ""))
			engine ()->addImportPath (cand);

		rootContext ()->setContextProperty ("quarkListModel", Model_);
		rootContext ()->setContextProperty ("colorProxy",
				new Util::ColorThemeProxy (proxy->GetColorThemeManager (), this));
		engine ()->addImageProvider ("ThemeIcons", new Util::ThemeImageProvider (proxy));
		setSource (QUrl::fromLocalFile (file));

		connect (rootObject (),
				SIGNAL (closeRequested ()),
				this,
				SLOT (deleteLater ()));
		connect (rootObject (),
				SIGNAL (moveRequested (QString, QString, int)),
				this,
				SLOT (moveQuark (QString, QString, int)));
		connect (rootObject (),
				SIGNAL (quarkClassHovered (QString)),
				this,
				SIGNAL (quarkClassHovered (QString)));
		connect (rootObject (),
				SIGNAL (quarkRemoveRequested (QString)),
				this,
				SLOT (handleQuarkCloseRequested (QString)),
				Qt::QueuedConnection);
	}

	void QuarkOrderView::handleQuarkCloseRequested (const QString& qClass)
	{
		Manager_->RemoveQuark (qClass);

		for (int i = 0, rc = Model_->rowCount (); i < rc; ++i)
		{
			auto item = Model_->item (i);
			if (item->data (Util::UnhideListModel::Roles::ItemClass) == qClass)
			{
				Model_->removeRow (i);
				break;
			}
		}
	}

	namespace
	{
		int FindClassRow (QStandardItemModel *model, const QString& itemClass)
		{
			for (int i = 0, rc = model->rowCount (); i < rc; ++i)
			{
				auto item = model->item (i);
				if (item->data (Util::UnhideListModel::Roles::ItemClass).toString () == itemClass)
					return i;
			}
			return -1;
		}
	}

	void QuarkOrderView::moveQuark (const QString& from, const QString& to, int shift)
	{
		const auto fromPos = FindClassRow (Model_, from);
		auto toPos = FindClassRow (Model_, to);
		if (fromPos < 0 || toPos < 0)
		{
			qWarning () << Q_FUNC_INFO
					<< "incorrect classes"
					<< from
					<< to
					<< fromPos
					<< toPos;
			return;
		}

		toPos += shift;

		Manager_->MoveQuark (fromPos, toPos);

		if (fromPos < toPos)
			--toPos;
		Model_->insertRow (toPos, Model_->takeRow (fromPos));
	}
}
}
