/**********************************************************************
 * 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 "playlistmanager.h"
#include <memory>
#include <QStandardItem>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDomDocument>
#include <QtDebug>
#include <util/util.h>
#include <interfaces/lmp/iplaylistprovider.h>
#include "authmanager.h"
#include "accountsmanager.h"
#include "consts.h"

namespace LC
{
namespace LMP
{
namespace MP3Tunes
{
	PlaylistManager::PlaylistManager (QNetworkAccessManager *nam,
			AuthManager *authMgr, AccountsManager *accMgr, QObject *parent)
	: QObject (parent)
	, NAM_ (nam)
	, AuthMgr_ (authMgr)
	, AccMgr_ (accMgr)
	, Root_ (new QStandardItem ("mp3tunes.com"))
	{
		Root_->setEditable (false);
		connect (AuthMgr_,
				SIGNAL (sidReady (QString)),
				this,
				SLOT (requestPlaylists (QString)));

		connect (AccMgr_,
				SIGNAL (accountsChanged ()),
				this,
				SLOT (handleAccountsChanged ()),
				Qt::QueuedConnection);
	}

	QStandardItem* PlaylistManager::GetRoot () const
	{
		return Root_;
	}

	void PlaylistManager::Update ()
	{
		while (Root_->rowCount ())
			Root_->removeRow (0);
		AccItems_.clear ();
		AccPlaylists_.clear ();
		Infos_.clear ();

		const auto& accs = AccMgr_->GetAccounts ();
		for (const auto& acc : accs)
		{
			auto item = new QStandardItem (acc);
			item->setEditable (false);
			AccItems_ [acc] = item;
			Root_->appendRow (item);

			requestPlaylists (acc);
		}
	}

	boost::optional<Media::AudioInfo> PlaylistManager::GetMediaInfo (const QUrl& url) const
	{
		return Infos_.contains (url) ?
				boost::make_optional (Infos_ [url]) :
				boost::optional<Media::AudioInfo> ();
	}

	void PlaylistManager::requestPlaylists (const QString& accName)
	{
		const auto& sid = AuthMgr_->GetSID (accName);
		if (sid.isEmpty ())
			return;

		const auto& url = QString ("http://ws.mp3tunes.com/api/v1/lockerData?output=xml"
					"&sid=%1&partner_token=%2&type=playlist")
				.arg (sid)
				.arg (Consts::PartnerId);
		auto reply = NAM_->get (QNetworkRequest (url));
		reply->setProperty ("AccountName", accName);
		connect (reply,
				SIGNAL (finished ()),
				this,
				SLOT (handleGotPlaylists ()));
	}

	void PlaylistManager::handleGotPlaylists ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& accName = reply->property ("AccountName").toString ();
		const auto& data = reply->readAll ();

		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse reply";
			return;
		}

		auto playlistsRoot = AccItems_ [accName];
		auto& playlists = AccPlaylists_ [accName];

		auto plItem = doc.documentElement ()
				.firstChildElement ("playlistList")
				.firstChildElement ("item");
		while (!plItem.isNull ())
		{
			std::shared_ptr<void> (static_cast<void*> (0),
					[&plItem] (void*) { plItem = plItem.nextSiblingElement ("item"); });
			const auto& id = plItem.firstChildElement ("playlistId").text ();
			if (id == "INBOX" || id.isEmpty ())
				continue;

			const auto& title = plItem.firstChildElement ("playlistTitle").text ();
			auto item = new QStandardItem (title);
			item->setEditable (false);
			playlists [id] = item;
			playlistsRoot->appendRow (item);

			const auto& sid = AuthMgr_->GetSID (accName);
			const auto& url = QString ("http://ws.mp3tunes.com/api/v1/lockerData?output=xml"
					"&sid=%1&partner_token=%2&type=track&playlist_id=%3")
					.arg (sid)
					.arg (Consts::PartnerId)
					.arg (id);
			auto contentsReply = NAM_->get (QNetworkRequest (url));
			contentsReply->setProperty ("AccountName", accName);
			contentsReply->setProperty ("PlaylistID", id);
			connect (contentsReply,
					SIGNAL (finished ()),
					this,
					SLOT (handleGotPlaylistContents ()));
		}
	}

	void PlaylistManager::handleGotPlaylistContents ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& accName = reply->property ("AccountName").toString ();
		const auto& id = reply->property ("PlaylistID").toString ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse reply";
			return;
		}

		QList<QUrl> urls;
		QStringList compositions;

		auto trackItem = doc.documentElement ()
				.firstChildElement ("trackList")
				.firstChildElement ("item");
		while (!trackItem.isNull ())
		{
			auto getText = [&trackItem] (const QString& elem) -> QString
			{
				const auto& text = trackItem.firstChildElement (elem).text ();
				return text.isEmpty () ? "unknown" : text;
			};

			const auto& urlStr = getText ("playURL").toUtf8 ();
			const auto& url = QUrl::fromEncoded (urlStr);
			urls << url;

			Media::AudioInfo info;
			info.Artist_ = getText ("artistName");
			info.Album_ = getText ("albumTitle");
			info.Title_ = getText ("trackTitle");
			info.Length_ = getText ("trackLength").toInt () / 1000;

			compositions << QString::fromUtf8 ("%1 — %2 — %3")
					.arg (info.Artist_)
					.arg (info.Album_)
					.arg (info.Title_);

			Infos_ [url] = info;

			trackItem = trackItem.nextSiblingElement ("item");
		}

		auto plItem = AccPlaylists_ [accName] [id];

		if (urls.isEmpty ())
		{
			plItem->parent ()->removeRow (plItem->row ());
			AccPlaylists_ [accName].remove (id);
			return;
		}

		plItem->setData (QVariant::fromValue (urls), IPlaylistProvider::ItemRoles::SourceURLs);
		plItem->setToolTip ("<ul><li>" + compositions.join ("</li><li>") + "</li></ul>");
	}

	void PlaylistManager::handleAccountsChanged ()
	{
		Update ();
	}
}
}
}
