/**********************************************************************
 * 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 "joinconferencedialog.h"
#include <QSet>
#include <QPushButton>
#include <QtDebug>
#include "interfaces/azoth/iprotocol.h"
#include "interfaces/azoth/imucjoinwidget.h"
#include "interfaces/azoth/isupportbookmarks.h"
#include "interfaces/azoth/imucprotocol.h"
#include "xmlsettingsmanager.h"

namespace LeechCraft
{
namespace Azoth
{
	JoinConferenceDialog::JoinConferenceDialog (const QList<IAccount*>& accounts, QWidget *parent)
	: QDialog (parent)
	{
		Ui_.setupUi (this);
		setAttribute (Qt::WA_DeleteOnClose, true);

		Q_FOREACH (IAccount *acc, accounts)
		{
			if (!acc->IsShownInRoster ())
				continue;

			const auto proto = qobject_cast<IProtocol*> (acc->GetParentProtocol ());
			const auto mucProto = qobject_cast<IMUCProtocol*> (acc->GetParentProtocol ());
			if (!mucProto)
				continue;

			if (!Proto2Joiner_.contains (proto))
			{
				const auto joiner = mucProto->GetMUCJoinWidget ();
				if (!qobject_cast<IMUCJoinWidget*> (joiner))
				{
					qWarning () << Q_FUNC_INFO
							<< "joiner widget for account"
							<< acc->GetAccountID ()
							<< "is not a IMUCJoinWidget"
							<< joiner;
					continue;
				}
				Proto2Joiner_ [proto] = joiner;
			}

			if (auto supBms = qobject_cast<ISupportBookmarks*> (acc->GetQObject ()))
				for (const auto& item : supBms->GetBookmarkedMUCs ())
				{
					const QVariantMap& map = item.toMap ();
					const QString& name = map ["HumanReadableName"].toString ();
					if (name.isEmpty ())
						continue;

					Ui_.BookmarksBox_->addItem (QString ("%1 (%2 [%3])")
								.arg (name)
								.arg (acc->GetAccountName ())
								.arg (proto->GetProtocolName ()),
							map);
				}

			Ui_.AccountBox_->addItem (tr ("%1 (%2, %3)")
						.arg (acc->GetAccountName ())
						.arg (acc->GetOurNick ())
						.arg (proto->GetProtocolName ()),
					QVariant::fromValue<QObject*> (acc->GetQObject ()));

			const QString& key = "JoinHistory/" + acc->GetAccountID ();
			QVariantList list = XmlSettingsManager::Instance ()
					.GetRawValue (key).toList ();

			Q_FOREACH (const QVariant& var, list)
			{
				const QVariantMap& map = var.toMap ();
				const QString& name = map ["HumanReadableName"].toString ();
				if (name.isEmpty ())
					continue;

				Ui_.HistoryBox_->addItem (QString ("%1 (%2 [%3])")
							.arg (name)
							.arg (acc->GetAccountName ())
							.arg (proto->GetProtocolName ()),
						map);
			}
		}

		if (Ui_.HistoryBox_->count ())
			QMetaObject::invokeMethod (this,
					"on_HistoryBox__activated",
					Q_ARG (int, 0));
	}

	JoinConferenceDialog::~JoinConferenceDialog ()
	{
		qDeleteAll (Proto2Joiner_);
	}

	void JoinConferenceDialog::SetIdentifyingData (const QVariantMap& ident)
	{
		FillWidget (ident);
	}

	void JoinConferenceDialog::accept ()
	{
		QDialog::accept ();

		QObject *accObj = Ui_.AccountBox_->
				itemData (Ui_.AccountBox_->currentIndex ()).value<QObject*> ();

		if (!Ui_.JoinWidgetFrameLayout_->count ())
			return;

		QWidget *widget = Ui_.JoinWidgetFrameLayout_->
				itemAt (0)->widget ();
		IMUCJoinWidget *imjw =
				qobject_cast<IMUCJoinWidget*> (widget);

		if (!imjw)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to cast"
					<< widget
					<< "to IMUCJoinWidget";
			return;
		}

		const QVariantMap& data = imjw->GetIdentifyingData ();
		IAccount *acc = qobject_cast<IAccount*> (accObj);
		if (acc)
		{
			const QString& key = "JoinHistory/" + acc->GetAccountID ();
			QVariantList list = XmlSettingsManager::Instance ()
					.GetRawValue (key).toList ();

			Q_FOREACH (const QVariant& var, list)
				if (var.toMap () ["HumanReadableName"] == data ["HumanReadableName"])
				{
					list.removeAll (var);
					break;
				}

			list.prepend (QVariant (data));
			XmlSettingsManager::Instance ().SetRawValue (key, list);
		}
		else
			qWarning () << Q_FUNC_INFO
					<< "could not cast"
					<< accObj
					<< "to IAccount";

		imjw->Join (accObj);

		auto isb = qobject_cast<ISupportBookmarks*> (accObj);
		if (Ui_.AddToBookmarks_->checkState () != Qt::Checked || !isb)
			return;

		auto list = isb->GetBookmarkedMUCs ();
		list << data;
		isb->SetBookmarkedMUCs (list);
	}

	void JoinConferenceDialog::reject ()
	{
		QDialog::reject ();

		if (Ui_.JoinWidgetFrameLayout_->count ())
		{
			QWidget *widget = Ui_.JoinWidgetFrameLayout_->
					itemAt (0)->widget ();
			IMUCJoinWidget *imjw =
					qobject_cast<IMUCJoinWidget*> (widget);

			if (!imjw)
			{
				qWarning () << Q_FUNC_INFO
						<< "unable to cast"
						<< widget
						<< "to IMUCJoinWidget";
				return;
			}
			imjw->Cancel ();
		}
	}

	void JoinConferenceDialog::on_AccountBox__currentIndexChanged (int idx)
	{
		while (Ui_.JoinWidgetFrameLayout_->count ())
		{
			QLayoutItem *item = Ui_.JoinWidgetFrameLayout_->takeAt (0);
			disconnect (item->widget (),
					SIGNAL (validityChanged (bool)),
					this,
					SLOT (handleValidityChanged (bool)));
			item->widget ()->hide ();
		}

		QObject *accObj = Ui_.AccountBox_->itemData (idx).value<QObject*> ();
		IAccount *acc = qobject_cast<IAccount*> (accObj);
		if (!acc)
		{
			qWarning () << Q_FUNC_INFO
					<< "item at idx"
					<< idx
					<< "doesn't yield a valid IAccount:"
					<< Ui_.AccountBox_->itemData (idx);
			return;
		}

		const auto proto = qobject_cast<IProtocol*> (acc->GetParentProtocol ());
		if (!proto)
		{
			qWarning () << Q_FUNC_INFO
					<< accObj
					<< "returns an invalid IProtocol"
					<< acc->GetParentProtocol ();
			return;
		}

		QWidget *joiner = Proto2Joiner_ [proto];
		Ui_.JoinWidgetFrameLayout_->addWidget (joiner);
		joiner->show ();
		connect (joiner,
				SIGNAL (validityChanged (bool)),
				this,
				SLOT (handleValidityChanged (bool)));

		adjustSize ();

		qobject_cast<IMUCJoinWidget*> (joiner)->AccountSelected (accObj);
	}

	void JoinConferenceDialog::on_BookmarksBox__activated (int idx)
	{
		const QVariantMap& map = Ui_.BookmarksBox_->itemData (idx).toMap ();
		FillWidget (map);
	}

	void JoinConferenceDialog::on_HistoryBox__activated (int idx)
	{
		const QVariantMap& map = Ui_.HistoryBox_->itemData (idx).toMap ();
		FillWidget (map);
	}

	void JoinConferenceDialog::handleValidityChanged (bool isValid)
	{
		Ui_.ButtonBox_->button (QDialogButtonBox::Ok)->setEnabled (isValid);
	}

	void JoinConferenceDialog::FillWidget (const QVariantMap& map)
	{
		const QByteArray& id = map ["AccountID"].toByteArray ();

		bool accFound = false;
		for (int i = 0; i < Ui_.AccountBox_->count (); ++i)
		{
			QObject *accObj = Ui_.AccountBox_->itemData (i).value<QObject*> ();
			IAccount *acc = qobject_cast<IAccount*> (accObj);
			if (acc->GetAccountID () != id)
				continue;

			Ui_.AccountBox_->setCurrentIndex (i);

			const auto proto = qobject_cast<IProtocol*> (acc->GetParentProtocol ());
			if (!Proto2Joiner_.contains (proto))
			{
				qWarning () << Q_FUNC_INFO
						<< "Proto2Joiner_ doesn't contain protocol for account"
						<< accObj;
				return;
			}
			qobject_cast<IMUCJoinWidget*> (Proto2Joiner_ [proto])->
					SetIdentifyingData (map);

			accFound = true;
			break;
		}
		if (!accFound)
		{
			qWarning () << Q_FUNC_INFO
					<< "could not find account with ID"
					<< id
					<< "; full map follows:"
					<< map;
			return;
		}
	}
}
}
