/**********************************************************************
 * 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 "tabsessmanager.h"
#include <algorithm>
#include <QIcon>
#include <QTimer>
#include <QSettings>
#include <QApplication>
#include <QMenu>
#include <QtDebug>
#include <util/util.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/irootwindowsmanager.h>
#include <interfaces/core/ipluginsmanager.h>
#include <interfaces/core/icoretabwidget.h>
#include <interfaces/ihaverecoverabletabs.h>
#include <interfaces/ihavetabs.h>
#include "recinfo.h"
#include "sessionmenumanager.h"
#include "sessionsmanager.h"
#include "util.h"

namespace LeechCraft
{
namespace TabSessManager
{
	void Plugin::Init (ICoreProxy_ptr proxy)
	{
		Util::InstallTranslator ("tabsessmanager");

		UncloseMenu_ = new QMenu (tr ("Unclose tabs"));

		SessionsMgr_ = new SessionsManager { proxy };

		SessionMenuMgr_ = new SessionMenuManager;
		connect (SessionMenuMgr_,
				SIGNAL (loadRequested (QString)),
				SessionsMgr_,
				SLOT (loadCustomSession (QString)));
		connect (SessionMenuMgr_,
				SIGNAL (addRequested (QString)),
				SessionsMgr_,
				SLOT (addCustomSession (QString)));
		connect (SessionMenuMgr_,
				SIGNAL (deleteRequested (QString)),
				SessionsMgr_,
				SLOT (deleteCustomSession (QString)));
		connect (SessionMenuMgr_,
				SIGNAL (saveCustomSessionRequested ()),
				SessionsMgr_,
				SLOT (saveCustomSession ()));

		connect (SessionsMgr_,
				SIGNAL (gotCustomSession (QString)),
				SessionMenuMgr_,
				SLOT (addCustomSession (QString)));

		Proxy_ = proxy;

		for (const auto& name : SessionsMgr_->GetCustomSessions ())
			SessionMenuMgr_->addCustomSession (name);
	}

	void Plugin::SecondInit ()
	{
		QTimer::singleShot (5000,
				SessionsMgr_,
				SLOT (recover ()));
	}

	QByteArray Plugin::GetUniqueID () const
	{
		return "org.LeechCraft.TabSessManager";
	}

	void Plugin::Release ()
	{
		QSettings settings (QCoreApplication::organizationName (),
				QCoreApplication::applicationName () + "_TabSessManager");
		settings.setValue ("CleanShutdown", true);
	}

	QString Plugin::GetName () const
	{
		return "TabSessManager";
	}

	QString Plugin::GetInfo () const
	{
		return tr ("Manages sessions of tabs in LeechCraft.");
	}

	QIcon Plugin::GetIcon () const
	{
		return {};
	}

	QSet<QByteArray> Plugin::GetPluginClasses () const
	{
		QSet<QByteArray> result;
		result << "org.LeechCraft.Core.Plugins/1.0";
		return result;
	}

	QList<QAction*> Plugin::GetActions (ActionsEmbedPlace place) const
	{
		switch (place)
		{
		case ActionsEmbedPlace::ToolsMenu:
			return
			{
				SessionMenuMgr_->GetSessionsMenu ()->menuAction (),
				UncloseMenu_->menuAction ()
			};
		case ActionsEmbedPlace::CommonContextMenu:
			return { UncloseMenu_->menuAction () };
		default:
			return {};
		}
	}

	void Plugin::hookTabIsRemoving (IHookProxy_ptr, int index, int windowId)
	{
		const auto rootWM = Proxy_->GetRootWindowsManager ();
		const auto tabWidget = rootWM->GetTabWidget (windowId);
		const auto widget = tabWidget->Widget (index);

		handleRemoveTab (widget);
		SessionsMgr_->handleRemoveTab (widget);
	}

	void Plugin::handleRemoveTab (QWidget *widget)
	{
		auto tab = qobject_cast<ITabWidget*> (widget);
		if (!tab)
			return;

		auto recTab = qobject_cast<IRecoverableTab*> (widget);
		if (!recTab)
			return;

		const auto& recoverData = recTab->GetTabRecoverData ();
		if (recoverData.isEmpty ())
			return;

		TabUncloseInfo info
		{
			{
				recoverData,
				GetSessionProps (widget)
			},
			qobject_cast<IHaveRecoverableTabs*> (tab->ParentMultiTabs ())
		};

		const auto rootWM = Proxy_->GetRootWindowsManager ();
		const auto winIdx = rootWM->GetWindowForTab (tab);
		const auto tabIdx = rootWM->GetTabWidget (winIdx)->IndexOf (widget);
		info.RecInfo_.DynProperties_.append ({ "TabSessManager/Position", tabIdx });

		const auto pos = std::find_if (UncloseAct2Data_.begin (), UncloseAct2Data_.end (),
				[&info] (const TabUncloseInfo& that) { return that.RecInfo_.Data_ == info.RecInfo_.Data_; });
		if (pos != UncloseAct2Data_.end ())
		{
			auto act = pos.key ();
			UncloseMenu_->removeAction (act);
			UncloseAct2Data_.erase (pos);
			delete act;
		}

		const auto& fm = UncloseMenu_->fontMetrics ();
		const QString& elided = fm.elidedText (recTab->GetTabRecoverName (), Qt::ElideMiddle, 300);
		QAction *action = new QAction (recTab->GetTabRecoverIcon (), elided, this);
		UncloseAct2Data_ [action] = info;

		connect (action,
				SIGNAL (triggered ()),
				this,
				SLOT (handleUnclose ()));

		if (UncloseMenu_->defaultAction ())
			UncloseMenu_->defaultAction ()->setShortcut (QKeySequence ());
		UncloseMenu_->insertAction (UncloseMenu_->actions ().value (0), action);
		UncloseMenu_->setDefaultAction (action);
		action->setShortcut (QString ("Ctrl+Shift+T"));
	}

	void Plugin::handleUnclose ()
	{
		auto action = qobject_cast<QAction*> (sender ());
		if (!action)
		{
			qWarning () << Q_FUNC_INFO
					<< "sender is not an action:"
					<< sender ();
			return;
		}

		if (!UncloseAct2Data_.contains (action))
			return;

		action->deleteLater ();

		auto data = UncloseAct2Data_.take (action);
		if (UncloseMenu_->defaultAction () == action)
		{
			auto nextAct = UncloseMenu_->actions ().value (1);
			if (nextAct)
			{
				UncloseMenu_->setDefaultAction (nextAct);
				nextAct->setShortcut (QString ("Ctrl+Shift+T"));
			}
		}
		UncloseMenu_->removeAction (action);

		data.Plugin_->RecoverTabs (QList<TabRecoverInfo> () << data.RecInfo_);
	}
}
}

LC_EXPORT_PLUGIN (leechcraft_tabsessmanager, LeechCraft::TabSessManager::Plugin);
