/**********************************************************************
 * 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 "bodyfetch.h"
#include <cstring>
#include <QIcon>
#include <interfaces/iscriptloader.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ipluginsmanager.h>
#include <util/xpc/util.h>
#include <util/sys/paths.h>
#include "workerobject.h"

namespace LeechCraft
{
namespace Aggregator
{
namespace BodyFetch
{
	void Plugin::Init (ICoreProxy_ptr proxy)
	{
		StorageDir_ = Util::CreateIfNotExists ("aggregator/bodyfetcher/storage");

		const int suffixLength = std::strlen (".html");
		for (int i = 0; i < 10; ++i)
		{
			const QString& name = QString::number (i);
			if (!StorageDir_.exists (name))
				StorageDir_.mkdir (name);
			else
			{
				QDir dir = StorageDir_;
				dir.cd (name);
				Q_FOREACH (QString name, dir.entryList ())
				{
					name.chop (suffixLength);
					FetchedItems_ << name.toLongLong ();
				}
			}
		}

		WO_ = 0;
		Proxy_ = proxy;
	}

	void Plugin::SecondInit ()
	{
		WO_ = new WorkerObject (this);

		IScriptLoader *loader = Proxy_->GetPluginsManager ()->
				GetAllCastableTo<IScriptLoader*> ().value (0, 0);
		if (!loader)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to find a suitable loader, aborting";
			return;
		}

		const auto& inst = loader->CreateScriptLoaderInstance ("aggregator/recipes/");
		if (!inst)
		{
			qWarning () << Q_FUNC_INFO
					<< "got a null script loader instance";
			return;
		}

		inst->AddGlobalPrefix ();
		inst->AddLocalPrefix ();

		WO_->SetLoaderInstance (inst);

		connect (WO_,
				SIGNAL (downloadRequested (QUrl)),
				this,
				SLOT (handleDownload (QUrl)));
		connect (WO_,
				SIGNAL (newBodyFetched (quint64)),
				this,
				SLOT (handleBodyFetched (quint64)),
				Qt::QueuedConnection);
		connect (this,
				SIGNAL (downloadFinished (QUrl, QString)),
				WO_,
				SLOT (handleDownloadFinished (QUrl, QString)));
	}

	QByteArray Plugin::GetUniqueID () const
	{
		return "org.LeechCraft.Aggregator.BodyFetch";
	}

	void Plugin::Release ()
	{
		delete WO_;
	}

	QString Plugin::GetName () const
	{
		return "Aggregator BodyFetch";
	}

	QString Plugin::GetInfo () const
	{
		return tr ("Fetches full bodies of news items following links in them.");
	}

	QIcon Plugin::GetIcon () const
	{
		static QIcon icon ("lcicons:/aggregator/bodyfetch/resources/images/bodyfetch.svg");
		return icon;
	}

	QSet<QByteArray> Plugin::GetPluginClasses () const
	{
		QSet<QByteArray> result;
		result << "org.LeechCraft.Aggregator.GeneralPlugin/1.0";
		return result;
	}

	void Plugin::hookItemLoad (IHookProxy_ptr, Item *item)
	{
		if (!FetchedItems_.contains (item->ItemID_))
			return;

		const quint64 id = item->ItemID_;
		if (!ContentsCache_.contains (id))
		{
			QDir dir = StorageDir_;

			dir.cd (QString::number (id % 10));
			QFile file (dir.filePath (QString ("%1.html").arg (id)));
			if (!file.open (QIODevice::ReadOnly))
			{
				qWarning () << Q_FUNC_INFO
						<< "unable to open file:"
						<< file.fileName ()
						<< file.errorString ();
				return;
			}

			ContentsCache_ [id] = QString::fromUtf8 (file.readAll ());
		}

		const QString& contents = ContentsCache_ [id];
		if (!contents.isEmpty ())
			item->Description_ = contents;
	}

	void Plugin::hookGotNewItems (IHookProxy_ptr, QVariantList items)
	{
		if (!WO_ || !WO_->IsOk ())
			return;

		WO_->AppendItems (items);
	}

	void Plugin::handleDownload (QUrl url)
	{
		const QString& temp = Util::GetTemporaryName ("agg_bodyfetcher");

		const Entity& e = Util::MakeEntity (url,
				temp,
				Internal |
					DoNotNotifyUser |
					DoNotSaveInHistory |
					OnlyDownload |
					NotPersistent);
		int id = -1;
		QObject *obj = 0;
		emit delegateEntity (e, &id, &obj);
		if (id == -1)
		{
			qWarning () << Q_FUNC_INFO
					<< "delegation failed";
			return;
		}

		Jobs_ [id] = qMakePair (url, temp);

		connect (obj,
				SIGNAL (jobFinished (int)),
				this,
				SLOT (handleJobFinished (int)),
				Qt::UniqueConnection);
	}

	void Plugin::handleJobFinished (int id)
	{
		if (!Jobs_.contains (id))
			return;

		const QPair<QUrl, QString>& job = Jobs_.take (id);

		emit downloadFinished (job.first, job.second);
	}

	void Plugin::handleBodyFetched (quint64 id)
	{
		FetchedItems_ << id;
	}
}
}
}

LC_EXPORT_PLUGIN (leechcraft_aggregator_bodyfetch, LeechCraft::Aggregator::BodyFetch::Plugin);
