/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2013  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 "servicediscoverywidget.h"
#include <QToolBar>
#include <QComboBox>
#include <QLineEdit>
#include <QTimer>
#include <QMenu>
#include "interfaces/azoth/iaccount.h"
#include "interfaces/azoth/ihaveservicediscovery.h"
#include "core.h"

namespace LeechCraft
{
namespace Azoth
{
	QObject* ServiceDiscoveryWidget::S_ParentMultiTabs_ = 0;

	void ServiceDiscoveryWidget::SetParentMultiTabs (QObject *parent)
	{
		S_ParentMultiTabs_ = parent;
	}

	ServiceDiscoveryWidget::ServiceDiscoveryWidget (QWidget *parent)
	: QWidget (parent)
	, Toolbar_ (new QToolBar)
	, AccountBox_ (new QComboBox)
	, AddressLine_ (new QLineEdit)
	, DiscoveryTimer_ (new QTimer (this))
	{
		Ui_.setupUi (this);

		DiscoveryTimer_->setSingleShot (true);
		DiscoveryTimer_->setInterval (1500);

		Toolbar_->addWidget (AccountBox_);
		Toolbar_->addWidget (AddressLine_);

		connect (AccountBox_,
				SIGNAL (currentIndexChanged (int)),
				this,
				SLOT (discover ()));
		connect (AddressLine_,
				SIGNAL (textEdited (const QString&)),
				this,
				SLOT (handleDiscoveryAddressChanged ()));
		connect (AddressLine_,
				SIGNAL (returnPressed ()),
				this,
				SLOT (discover ()));
		connect (DiscoveryTimer_,
				SIGNAL (timeout ()),
				this,
				SLOT (discover ()));

		Q_FOREACH (IAccount *acc, Core::Instance ().GetAccounts ())
		{
			auto ihsd = qobject_cast<IHaveServiceDiscovery*> (acc->GetQObject ());
			if (!ihsd)
				continue;

			auto proto = qobject_cast<IProtocol*> (acc->GetParentProtocol ());
			if (!proto)
			{
				qWarning () << Q_FUNC_INFO
						<< acc->GetParentProtocol ()
						<< "doesn't implement IProtocol";
				continue;
			}

			const QString& protoName = proto->GetProtocolName ();
			AccountBox_->addItem (acc->GetAccountName () + "(" + protoName + ")",
					QVariant::fromValue<QObject*> (acc->GetQObject ()));
		}
	}

	TabClassInfo ServiceDiscoveryWidget::GetTabClassInfo () const
	{
		TabClassInfo sdTab =
		{
			"SD",
			tr ("Service discovery"),
			tr ("A service discovery tab that allows one to discover "
				"capabilities of remote entries"),
			QIcon ("lcicons:/plugins/azoth/resources/images/sdtab.svg"),
			55,
			TFOpenableByRequest
		};
		return sdTab;
	}

	QObject* ServiceDiscoveryWidget::ParentMultiTabs ()
	{
		return S_ParentMultiTabs_;
	}

	void ServiceDiscoveryWidget::Remove ()
	{
		emit removeTab (this);
		deleteLater ();
	}

	QToolBar* ServiceDiscoveryWidget::GetToolBar () const
	{
		return Toolbar_;
	}

	void ServiceDiscoveryWidget::SetAccount (QObject *obj)
	{
		const int pos = AccountBox_->findData (QVariant::fromValue<QObject*> (obj));
		if (pos == -1)
			return;

		AccountBox_->setCurrentIndex (pos);
		auto ihsd = qobject_cast<IHaveServiceDiscovery*> (obj);
		const auto& query = ihsd->GetDefaultQuery ();
		if (query.isEmpty ())
			return;

		AddressLine_->setText (query);
		discover ();
	}

	void ServiceDiscoveryWidget::SetSDSession (ISDSession *session)
	{
		AddressLine_->setText (session->GetQuery ());
		SDSession_.reset (session);
		if (Ui_.DiscoveryTree_->selectionModel ())
			Ui_.DiscoveryTree_->selectionModel ()->deleteLater ();
		Ui_.DiscoveryTree_->setModel (session->GetRepresentationModel ());
	}

	void ServiceDiscoveryWidget::handleDiscoveryAddressChanged ()
	{
		DiscoveryTimer_->stop ();
		DiscoveryTimer_->start ();
	}

	void ServiceDiscoveryWidget::on_DiscoveryTree__customContextMenuRequested (const QPoint& point)
	{
		const QModelIndex& idx = Ui_.DiscoveryTree_->indexAt (point);
		if (!idx.isValid ())
			return;

		const QList<QPair<QByteArray, QString>>& actions =
				SDSession_->GetActionsFor (idx);
		if (actions.isEmpty ())
			return;

		QMenu *menu = new QMenu (tr ("Discovery actions"));
		for (auto i = actions.begin (), end = actions.end (); i != end; ++i)
			 menu->addAction (i->second)->setProperty ("Azoth/ID", i->first);

		QAction *result = menu->exec (Ui_.DiscoveryTree_->
					viewport ()->mapToGlobal (point));
		menu->deleteLater ();
		if (!result)
			return;

		const QByteArray& id = result->property ("Azoth/ID").toByteArray ();
		SDSession_->ExecuteAction (idx, id);
	}

	void ServiceDiscoveryWidget::discover ()
	{
		DiscoveryTimer_->stop ();

		if (Ui_.DiscoveryTree_->selectionModel ())
			Ui_.DiscoveryTree_->selectionModel ()->deleteLater ();
		Ui_.DiscoveryTree_->setModel (0);
		SDSession_.reset ();

		const int index = AccountBox_->currentIndex ();
		if (index == -1)
			return;

		const QString& address = AddressLine_->text ();
		if (address.isEmpty ())
			return;

		QObject *accObj = AccountBox_->itemData (index).value<QObject*> ();
		IHaveServiceDiscovery *ihsd = qobject_cast<IHaveServiceDiscovery*> (accObj);
		if (!ihsd)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to cast"
					<< accObj
					<< "to IHaveServiceDiscovery";
			return;
		}

		QObject *sessionObj = ihsd->CreateSDSession ();
		ISDSession *session = qobject_cast<ISDSession*> (sessionObj);
		if (!session)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to cast"
					<< sessionObj
					<< "to ISDSession; got it from"
					<< accObj;
			return;
		}

		session->SetQuery (address);
		SetSDSession (session);
	}
}
}
