/**********************************************************************
 * 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 "acceptlangwidget.h"
#include <QStandardItemModel>
#include "util/util.h"
#include "networkaccessmanager.h"
#include "core.h"

namespace LeechCraft
{
	AcceptLangWidget::AcceptLangWidget (QWidget *parent)
	: QWidget (parent)
	, Model_ (new QStandardItemModel (this))
	{
		Ui_.setupUi (this);
		Ui_.LangsTree_->setModel (Model_);

		connect (Core::Instance ().GetNetworkAccessManager (),
				SIGNAL (acceptableLanguagesChanged ()),
				this,
				SLOT (reject ()));
		reject ();

		for (int i = 0; i < QLocale::LastCountry; ++i)
			Ui_.Country_->addItem (QLocale::countryToString (static_cast<QLocale::Country> (i)), i);
		Ui_.Country_->model ()->sort (0);

		for (int i = 0; i < QLocale::LastLanguage; ++i)
		{
			if (i == QLocale::C)
				continue;

			Ui_.Language_->addItem (QLocale::languageToString (static_cast<QLocale::Language> (i)), i);
		}
		Ui_.Language_->model ()->sort (0);
		on_Language__currentIndexChanged (Ui_.Language_->currentIndex ());
	}

	void AcceptLangWidget::AddLocale (const QLocale& locale)
	{
		QList<QStandardItem*> items;
		items << new QStandardItem (QLocale::languageToString (locale.language ()));
		items << new QStandardItem (QLocale::countryToString (locale.country ()));
		items << new QStandardItem (Util::GetInternetLocaleName (locale));
		Model_->appendRow (items);
		items.first ()->setData (locale, Roles::LocaleObj);
	}
	
	void AcceptLangWidget::accept ()
	{
		QList<QLocale> locales;
		for (int i = 0; i < Model_->rowCount (); ++i)
			locales << Model_->item (i)->data (Roles::LocaleObj).toLocale ();

		auto qnam = Core::Instance ().GetNetworkAccessManager ();
		auto nam = qobject_cast<NetworkAccessManager*> (qnam);
		nam->SetAcceptLangs (locales);
	}

	void AcceptLangWidget::reject ()
	{
		Model_->clear ();
		Model_->setHorizontalHeaderLabels (QStringList (tr ("Language")) << tr ("Country") << tr ("Code"));

		auto qnam = Core::Instance ().GetNetworkAccessManager ();
		auto nam = qobject_cast<NetworkAccessManager*> (qnam);
		Q_FOREACH (const QLocale& locale, nam->GetAcceptLangs ())
			AddLocale (locale);
	}

	namespace
	{
		template<typename T>
		T GetValue (const QComboBox *box)
		{
			const int idx = box->currentIndex ();
			if (idx <= 0)
				return T ();

			const int val = box->itemData (idx).toInt ();
			return static_cast<T> (val);
		}
	}

	void AcceptLangWidget::on_Add__released ()
	{
		const auto country = GetValue<QLocale::Country> (Ui_.Country_);
		const auto lang = GetValue<QLocale::Language> (Ui_.Language_);
		AddLocale (QLocale (lang, country));
	}

	void AcceptLangWidget::on_Remove__released ()
	{
		const auto& idx = Ui_.LangsTree_->currentIndex ();
		if (!idx.isValid ())
			return;

		Model_->removeRow (idx.row ());
	}

	void AcceptLangWidget::on_MoveUp__released ()
	{
		QStandardItem *item = Model_->itemFromIndex (Ui_.LangsTree_->currentIndex ());
		if (!item || !item->row ())
			return;

		const int row = item->row ();
		Model_->insertRow (row - 1, Model_->takeRow (row));
	}

	void AcceptLangWidget::on_MoveDown__released ()
	{
		QStandardItem *item = Model_->itemFromIndex (Ui_.LangsTree_->currentIndex ());
		if (!item || item->row () == Model_->rowCount () - 1)
			return;

		const int row = item->row ();
		auto items = Model_->takeRow (row);
		Model_->insertRow (row + 1, items);
	}

	void AcceptLangWidget::on_Language__currentIndexChanged (int)
	{
		Ui_.Country_->clear ();

		const auto lang = GetValue<QLocale::Language> (Ui_.Language_);
		auto countries = QLocale::countriesForLanguage (lang);
		if (!countries.contains (QLocale::AnyCountry))
			countries << QLocale::AnyCountry;
		Q_FOREACH (QLocale::Country c, countries)
			Ui_.Country_->addItem (QLocale::countryToString (c), c);
		Ui_.Country_->model ()->sort (0);
	}
}
