/**********************************************************************
 * 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 "tablistview.h"
#include <QStandardItemModel>
#include <QMainWindow>

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

#include <QtDebug>
#include <util/util.h>
#include <util/sys/paths.h>
#include <util/qml/colorthemeproxy.h>
#include <util/qml/themeimageprovider.h>
#include <util/gui/unhoverdeletemixin.h>
#include <util/models/rolenamesmixin.h>
#include <interfaces/ihavetabs.h>
#include <interfaces/core/icoretabwidget.h>

namespace LeechCraft
{
namespace SB2
{
	namespace
	{
		class TabsListModel : public Util::RoleNamesMixin<QStandardItemModel>
		{
		public:
			enum Roles
			{
				TabIcon = Qt::UserRole + 1,
				TabName,
				TabWidgetObj
			};

			TabsListModel (QObject *parent)
			: RoleNamesMixin<QStandardItemModel> (parent)
			{
				QHash<int, QByteArray> names;
				names [Roles::TabIcon] = "tabIcon";
				names [Roles::TabName] = "tabName";
				setRoleNames (names);
			}
		};
	}

	TabListView::TabListView (const QByteArray& tc, const QList<QWidget*>& widgets,
			ICoreTabWidget *ictw, QMainWindow *win, ICoreProxy_ptr proxy, QWidget *parent)
#if QT_VERSION < 0x050000
	: QDeclarativeView (parent)
#else
	: QQuickView (parent->windowHandle ())
#endif
	, Proxy_ (proxy)
	, ICTW_ (ictw)
	, MW_ (win)
	, TC_ (tc)
	, Model_ (new TabsListModel (this))
	, UnhoverDeleteMixin_ (new Util::UnhoverDeleteMixin (this))
	{
		const auto& file = Util::GetSysPath (Util::SysPath::QML, "sb2", "TabListView.qml");
		if (file.isEmpty ())
		{
			qWarning () << Q_FUNC_INFO
					<< "file not found";
			deleteLater ();
			return;
		}

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

		QString longestText;

		for (auto w : widgets)
		{
			const int idx = ictw->IndexOf (w);
			if (idx < 0)
			{
				qWarning () << Q_FUNC_INFO
						<< "unknown widget"
						<< w;
				continue;
			}

			auto item = new QStandardItem;

			const auto& tabText = ictw->TabText (idx);
			item->setData (tabText, TabsListModel::Roles::TabName);
			if (tabText.size () > longestText.size ())
				longestText = tabText;

			const auto& px = ictw->TabIcon (idx).pixmap (32, 32);
			item->setData (Util::GetAsBase64Src (px.toImage ()), TabsListModel::Roles::TabIcon);

			item->setData (QVariant::fromValue<QObject*> (w), TabsListModel::Roles::TabWidgetObj);

			Model_->appendRow (item);

			auto itw = qobject_cast<ITabWidget*> (w);
			auto parent	= itw->ParentMultiTabs ();
			connect (parent,
					SIGNAL (removeTab (QWidget*)),
					this,
					SLOT (handleTabRemoved (QWidget*)));
		}

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

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

		connect (rootObject (),
				SIGNAL (closeRequested ()),
				this,
				SLOT (deleteLater ()));
		connect (rootObject (),
				SIGNAL (tabSwitchRequested (int)),
				this,
				SLOT (switchToItem (int)));
		connect (rootObject (),
				SIGNAL (tabCloseRequested (int)),
				this,
				SLOT (closeItem (int)));
	}

	TabListView::~TabListView ()
	{
		Model_->clear ();
	}

	QByteArray TabListView::GetTabClass () const
	{
		return TC_;
	}

	void TabListView::HandleLauncherHovered ()
	{
		UnhoverDeleteMixin_->Stop ();
	}

	void TabListView::HandleLauncherUnhovered ()
	{
		UnhoverDeleteMixin_->Start (1200);
	}

	void TabListView::handleTabRemoved (QWidget *widget)
	{
		for (int i = 0; i < Model_->rowCount (); ++i)
		{
			auto item = Model_->item (i);
			auto widgetObj = item->data (TabsListModel::Roles::TabWidgetObj).value<QObject*> ();
			if (widgetObj != widget)
				continue;

			Model_->removeRow (i);
			return;
		}
	}

	void TabListView::switchToItem (int idx)
	{
		auto item = Model_->item (idx);
		if (!item)
		{
			qWarning () << Q_FUNC_INFO
					<< "null item at"
					<< idx;
			return;
		}

		auto widgetObj = item->data (TabsListModel::Roles::TabWidgetObj).value<QObject*> ();
		ICTW_->setCurrentWidget (static_cast<QWidget*> (widgetObj));
		MW_->activateWindow ();
		MW_->raise ();
		deleteLater ();
	}

	void TabListView::closeItem (int idx)
	{
		auto item = Model_->item (idx);
		if (!item)
		{
			qWarning () << Q_FUNC_INFO
					<< "null item at"
					<< idx;
			return;
		}

		auto widgetObj = item->data (TabsListModel::Roles::TabWidgetObj).value<QObject*> ();
		auto itw = qobject_cast<ITabWidget*> (widgetObj);
		itw->Remove ();
	}
}
}
