/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2010-2011  Oleg Linkin
 *
 * 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 "deliciousapi.h"
#include <QtDebug>
#include <QStringList>
#include <QDateTime>
#include <QXmlStreamReader>

namespace LeechCraft
{
namespace Poshuku
{
namespace OnlineBookmarks
{
namespace Delicious
{
	DeliciousApi::DeliciousApi ()
	{
	}

	QString DeliciousApi::GetAuthUrl (const DeliciousAccount::AuthType& at) const
	{
		if (at & DeliciousAccount::ATHttpAuth)
			return "https://%1:%2@api.del.icio.us/v1/posts/update";

		qWarning () << Q_FUNC_INFO << "unknown auth type" << at;
		return QString ();
	}

	QString DeliciousApi::GetUploadUrl (const DeliciousAccount::AuthType& at) const
	{
		if (at & DeliciousAccount::ATHttpAuth)
			return "https://%1:%2@api.del.icio.us/v1/posts/add?";

		qWarning () << Q_FUNC_INFO << "unknown auth type" << at;
		return QString ();
	}

	QByteArray DeliciousApi::GetUploadPayload (const QVariant& bookmark)
	{
		QVariantMap map = bookmark.toMap ();

		return QString ("&url=%1&description=%2&tags=%3")
				.arg (map ["URL"].toString (),
						map ["Title"].toString (),
						map ["Tags"].toString ().split (',').join (" ")).toUtf8 ();
	}

	QString DeliciousApi::GetDownloadUrl (const DeliciousAccount::AuthType& at) const
	{
		if (at & DeliciousAccount::ATHttpAuth)
			return "https://%1:%2@api.del.icio.us/v1/posts/all?";

		qWarning () << Q_FUNC_INFO << "unknown auth type" << at;
		return QString ();
	}

	QByteArray DeliciousApi::GetDownloadPayload (const QDateTime& from)
	{
		if (from.isNull ())
			return QString ("&meta=yes").toUtf8 ();
		else
			return QString ("&fromdt=%1&meta=yes").arg (from.toString ("yyyy-MM-ddThh:mm:ssZ")).toUtf8 ();
	}

	QVariantList DeliciousApi::ParseDownloadReply (const QByteArray& content)
	{
		QVariantList list;
		QVariantMap record;
		QXmlStreamReader xml (content);
		while (!xml.atEnd () &&
				!xml.hasError ())
		{
			QXmlStreamReader::TokenType token = xml.readNext ();

			if (token == QXmlStreamReader::StartDocument)
				continue;

			if (token == QXmlStreamReader::StartElement &&
					xml.name() == "post")
			{
				record ["URL"] = xml.attributes ().value ("href").toString ();
				record ["Title"] = xml.attributes ().value ("description").toString ();;
				record ["Tags"] = xml.attributes ().value ("tag").toString ();
				list << record;
			}
		}

		qWarning () << Q_FUNC_INFO
				<< "Parsing finished with error"
				<< xml.errorString ();

		return list;
	}

	bool DeliciousApi::ParseAuthReply (const QByteArray& content)
	{
		QXmlStreamReader xml (content);
		while (!xml.atEnd () &&
				!xml.hasError ())
		{
			QXmlStreamReader::TokenType token = xml.readNext ();

			if (token == QXmlStreamReader::StartDocument)
				continue;

			if (token == QXmlStreamReader::StartElement &&
					xml.name() == "update" &&
					xml.attributes ().hasAttribute ("time"))
				return true;
		}

		qWarning () << Q_FUNC_INFO
				<< "Parsing finished with error"
				<< xml.errorString ();

		return false;
	}

	bool DeliciousApi::ParseUploadReply (const QByteArray& content)
	{
		QXmlStreamReader xml (content);
		while (!xml.atEnd () &&
				!xml.hasError ())
		{
			QXmlStreamReader::TokenType token = xml.readNext ();

			if (token == QXmlStreamReader::StartDocument)
				continue;

			if (token == QXmlStreamReader::StartElement &&
					xml.name() == "result" &&
					xml.attributes ().hasAttribute ("code") &&
					xml.attributes ().value ("code") == "done")
				return true;
		}

		qWarning () << Q_FUNC_INFO
				<< "Parsing finished with error"
				<< xml.errorString ();

		return false;
	}

}
}
}
}

