/**********************************************************************
 * 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 "chattabnetworkaccessmanager.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QtDebug>
#include <QBuffer>
#include <util/sll/delayedexecutor.h>
#include <util/threads/futures.h>
#include "avatarsmanager.h"
#include "core.h"
#include "resourcesmanager.h"

namespace LeechCraft
{
namespace Azoth
{
	namespace
	{
		class AvatarReply : public QNetworkReply
		{
			QBuffer Buffer_;
		public:
			AvatarReply (const QNetworkRequest&, AvatarsManager*);

			qint64 bytesAvailable () const override;
			qint64 readData (char* data, qint64 maxlen) override;
			void abort () override;
		private:
			void HandleImage (const QImage&);
		};

		AvatarReply::AvatarReply (const QNetworkRequest& req, AvatarsManager *am)
		{
			open (QIODevice::ReadOnly);

			setHeader (QNetworkRequest::ContentTypeHeader, QByteArray { "image/png" });
			setAttribute (QNetworkRequest::HttpStatusCodeAttribute, 200);
			setAttribute (QNetworkRequest::HttpReasonPhraseAttribute, QByteArray { "OK" });

			Util::ExecuteLater ([this] { emit metaDataChanged (); });

			const auto& entryIdPath = req.url ().path ().section ('/', 1, 1);
			const auto& entryId = QString::fromUtf8 (QByteArray::fromBase64 (entryIdPath.toLatin1 ()));

			const auto entryObj = Core::Instance ().GetEntry (entryId);
			if (!entryObj)
			{
				Util::ExecuteLater ([this]
						{ HandleImage (ResourcesManager::Instance ().GetDefaultAvatar (32)); });
				return;
			}

			Util::Sequence (this, am->GetAvatar (entryObj, IHaveAvatars::Size::Thumbnail)) >>
					[this] (const QImage& image) { HandleImage (image); };
		}

		qint64 AvatarReply::bytesAvailable () const
		{
			return QNetworkReply::bytesAvailable () + Buffer_.bytesAvailable ();
		}

		qint64 AvatarReply::readData (char *data, qint64 maxlen)
		{
			return Buffer_.read (data, maxlen);
		}

		void AvatarReply::abort ()
		{
			qWarning () << Q_FUNC_INFO
					<< "cannot abort";
		}

		void AvatarReply::HandleImage (const QImage& image)
		{
			Buffer_.open (QIODevice::WriteOnly);
			image.save (&Buffer_, "PNG", 100);
			Buffer_.close ();

			Buffer_.open (QIODevice::ReadOnly);

			setHeader (QNetworkRequest::ContentLengthHeader, Buffer_.bytesAvailable ());
			emit downloadProgress (Buffer_.size (), Buffer_.size ());

			emit readyRead ();
		}
	}

	ChatTabNetworkAccessManager::ChatTabNetworkAccessManager (AvatarsManager *am, QObject *parent)
	: QNetworkAccessManager { parent }
	, AvatarsMgr_ { am }
	{
	}

	QNetworkReply* ChatTabNetworkAccessManager::createRequest (Operation op,
			const QNetworkRequest& request, QIODevice *outgoingData)
	{
		const auto& url = request.url ();
		if (url.scheme () == "azoth" && url.host () == "avatar")
			return new AvatarReply { request, AvatarsMgr_ };

		return QNetworkAccessManager::createRequest (op, request, outgoingData);
	}
}
}
