/**********************************************************************
 * 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 "searchwidget.h"
#include <QTimer>
#include <util/sys/resourceloader.h>
#include <util/threads/futures.h>
#include "interfaces/azoth/iaccount.h"
#include "interfaces/azoth/ihavesearch.h"
#include "interfaces/azoth/iextselfinfoaccount.h"
#include "core.h"
#include "xmlsettingsmanager.h"
#include "resourcesmanager.h"
#include "avatarsmanager.h"

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

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

	SearchWidget::SearchWidget (AvatarsManager *am, QWidget *parent)
	: QWidget { parent }
	, AvatarsManager_ { am }
	{
		Ui_.setupUi (this);

		connect (Ui_.Server_,
				SIGNAL (returnPressed ()),
				this,
				SLOT (search ()));

		const QIcon defaultAvatarIcon
		{
			QPixmap::fromImage (ResourcesManager::Instance ()
					.GetDefaultAvatar (Ui_.AccountBox_->iconSize ().width ()))
		};

		for (const auto acc : Core::Instance ().GetAccounts ())
		{
			const auto accObj = acc->GetQObject ();
			const auto search = qobject_cast<IHaveSearch*> (accObj);
			if (!search)
				continue;

			const auto self = qobject_cast<IExtSelfInfoAccount*> (accObj);

			const auto idx = Ui_.AccountBox_->count ();
			auto iconSetter = [this, self, idx] (const QImage& image)
			{
				QIcon icon { QPixmap::fromImage (image) };
				if (icon.isNull () && self)
					icon = self->GetAccountIcon ();
				if (!icon.isNull ())
					Ui_.AccountBox_->setItemIcon (idx, icon);
			};

			Ui_.AccountBox_->blockSignals (true);
			Ui_.AccountBox_->addItem (defaultAvatarIcon,
					acc->GetAccountName (),
					QVariant::fromValue<QObject*> (accObj));
			Ui_.AccountBox_->blockSignals (false);

			if (auto selfEntry = self ? self->GetSelfContact () : nullptr)
				Util::Sequence (this,
						AvatarsManager_->GetAvatar (selfEntry, IHaveAvatars::Size::Thumbnail)) >>
						iconSetter;
			else
				iconSetter ({});
		}

		Ui_.AccountBox_->blockSignals (true);
		Ui_.AccountBox_->blockSignals (false);
	}

	TabClassInfo SearchWidget::GetTabClassInfo () const
	{
		TabClassInfo searchTab =
		{
			"Search",
			tr ("Search"),
			tr ("A search tab allows one to search within IM services"),
			QIcon ("lcicons:/plugins/azoth/resources/images/searchtab.svg"),
			55,
			TFOpenableByRequest
		};
		return searchTab;
	}

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

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

	QToolBar* SearchWidget::GetToolBar () const
	{
		return 0;
	}

	IHaveSearch* SearchWidget::GetCurrentSearch () const
	{
		const int idx = Ui_.AccountBox_->currentIndex ();
		QObject *accObj = Ui_.AccountBox_->itemData (idx).value<QObject*> ();
		return qobject_cast<IHaveSearch*> (accObj);
	}

	void SearchWidget::search ()
	{
		IHaveSearch *search = GetCurrentSearch ();
		if (!search)
		{
			qWarning () << Q_FUNC_INFO
					<< "no current search object";
			return;
		}

		QObject *sessObj = search->CreateSearchSession ();
		ISearchSession *sess = qobject_cast<ISearchSession*> (sessObj);
		CurrentSess_.reset (sess);

		if (!sess)
		{
			qWarning () << Q_FUNC_INFO
					<< sessObj
					<< "doesn't implement ISearchSession";
			return;
		}

		sess->RestartSearch (Ui_.Server_->text ());

		if (Ui_.ResultsTree_->selectionModel ())
			Ui_.ResultsTree_->selectionModel ()->deleteLater ();
		Ui_.ResultsTree_->setModel (sess->GetRepresentationModel ());
	}

	void SearchWidget::on_AccountBox__activated (int)
	{
		IHaveSearch *s = GetCurrentSearch ();
		Ui_.Server_->setText (s->GetDefaultSearchServer ());

		QTimer::singleShot (0,
				this,
				SLOT (search ()));
	}
}
}
