/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2013  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 "authmanager.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QtDebug>
#include <QWebView>
#include <util/customcookiejar.h>
#include "xmlsettingsmanager.h"

namespace LeechCraft
{
namespace TouchStreams
{
	const QUrl AuthURL = QUrl::fromEncoded ("https://oauth.vk.com/authorize?client_id=3298289&redirect_uri=http%3A%2F%2Foauth.vk.com%2Fblank.html&response_type=token&scope=8&state=");

	AuthManager::AuthManager (ICoreProxy_ptr proxy, QObject *parent)
	: QObject (parent)
	, Proxy_ (proxy)
	, AuthNAM_ (new QNetworkAccessManager (this))
	, Cookies_ (new Util::CustomCookieJar)
	, ValidFor_ (0)
	, IsRequesting_ (false)
	{
		AuthNAM_->setCookieJar (Cookies_);

		const auto& cookies = XmlSettingsManager::Instance ()
				.property ("Cookies").toByteArray ();
		if (!cookies.isEmpty ())
			Cookies_->Load (cookies);
	}

	void AuthManager::GetAuthKey ()
	{
		if (Token_.isEmpty () ||
				ReceivedAt_.secsTo (QDateTime::currentDateTime ()) > ValidFor_)
		{
			RequestAuthKey ();
			return;
		}

		emit gotAuthKey (Token_);
	}

	void AuthManager::Reauth ()
	{
		auto view = new QWebView;
		view->setWindowTitle (tr ("VK.com authentication"));
		view->setWindowFlags (Qt::Window);
		view->resize (800, 600);
		view->page ()->setNetworkAccessManager (AuthNAM_);
		view->show ();

		view->setUrl (AuthURL);

		connect (view,
				SIGNAL (urlChanged (QUrl)),
				this,
				SLOT (handleViewUrlChanged (QUrl)));
	}

	void AuthManager::HandleError ()
	{
		IsRequesting_ = false;
	}

	void AuthManager::RequestURL (const QUrl& url)
	{
		qDebug () << Q_FUNC_INFO << url;
		auto reply = AuthNAM_->get (QNetworkRequest (url));
		connect (reply,
				SIGNAL (finished ()),
				this,
				SLOT (handleGotForm ()));
		connect (reply,
				SIGNAL(error (QNetworkReply::NetworkError)),
				this,
				SLOT (handleFormFetchError ()));
	}

	void AuthManager::RequestAuthKey ()
	{
		if (IsRequesting_)
			return;

		RequestURL (AuthURL);
		IsRequesting_ = true;
	}

	bool AuthManager::CheckIsBlank (QUrl location)
	{
		if (location.path () != "/blank.html")
			return false;

		location = QUrl::fromEncoded (location.toEncoded ().replace ('#', '?'));
		Token_ = location.queryItemValue ("access_token");
		ValidFor_ = location.queryItemValue ("expires_in").toInt ();
		ReceivedAt_ = QDateTime::currentDateTime ();
		qDebug () << Q_FUNC_INFO << Token_ << ValidFor_;
		IsRequesting_ = false;

		emit gotAuthKey (Token_);

		return true;
	}

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

		const auto& location = reply->header (QNetworkRequest::LocationHeader).toUrl ();
		if (location.isEmpty ())
		{
			Reauth ();
			return;
		}

		if (CheckIsBlank (location))
			return;

		RequestURL (location);
	}

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

		qWarning () << Q_FUNC_INFO
				<< reply->errorString ();

		HandleError ();
	}

	void AuthManager::handleViewUrlChanged (const QUrl& url)
	{
		if (!CheckIsBlank (url))
			return;

		XmlSettingsManager::Instance ().setProperty ("Cookies", Cookies_->Save ());
		sender ()->deleteLater ();
	}
}
}
