/**********************************************************************
 * 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 "networkdiskcache.h"
#include <QtDebug>
#include <QDateTime>
#include <QDir>
#include <QtConcurrentRun>
#include <QFutureWatcher>
#include <QTimer>
#include <QDirIterator>
#include <QMutexLocker>
#include "xmlsettingsmanager.h"

namespace LeechCraft
{
	NetworkDiskCache::NetworkDiskCache (QObject *parent)
	: QNetworkDiskCache (parent)
	, IsCollectingGarbage_ (false)
	, CurrentSize_ (-1)
	, InsertRemoveMutex_ (QMutex::Recursive)
	{
		setCacheDirectory (QDir::homePath () + "/.leechcraft/core/cache");

		XmlSettingsManager::Instance ()->RegisterObject ("CacheSize",
				this, "handleCacheSize");
		handleCacheSize ();
	}

	qint64 NetworkDiskCache::cacheSize () const
	{
		return CurrentSize_;
	}

	QIODevice* NetworkDiskCache::data (const QUrl& url)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		return QNetworkDiskCache::data (url);
	}

	void NetworkDiskCache::insert (QIODevice *device)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		CurrentSize_ += device->size ();
		QNetworkDiskCache::insert (device);
	}

	QNetworkCacheMetaData NetworkDiskCache::metaData (const QUrl& url)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		return QNetworkDiskCache::metaData (url);
	}

	QIODevice* NetworkDiskCache::prepare (const QNetworkCacheMetaData& metadata)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		return QNetworkDiskCache::prepare (metadata);
	}

	bool NetworkDiskCache::remove (const QUrl &url)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		return QNetworkDiskCache::remove (url);
	}

	void NetworkDiskCache::updateMetaData (const QNetworkCacheMetaData& metaData)
	{
		QMutexLocker lock (&InsertRemoveMutex_);
		QNetworkDiskCache::updateMetaData (metaData);
	}

	qint64 NetworkDiskCache::expire ()
	{
		if (CurrentSize_ < 0)
		{
			collectGarbage ();
			return maximumCacheSize () * 8 / 10;
		}

		if (CurrentSize_ > maximumCacheSize ())
			collectGarbage ();

		return CurrentSize_;
	}

	void NetworkDiskCache::handleCacheSize ()
	{
		setMaximumCacheSize (XmlSettingsManager::Instance ()->
				property ("CacheSize").toInt () * 1048576);
		expire ();
	}

	namespace
	{
		qint64 Collector (QString& cacheDirectory, qint64 goal, QMutex *fileOpMutex)
		{
			if (cacheDirectory.isEmpty ())
				return 0;

			qDebug () << Q_FUNC_INFO << "running..." << cacheDirectory;

			QDir::Filters filters = QDir::AllDirs | QDir:: Files | QDir::NoDotAndDotDot;
			QDirIterator it (cacheDirectory, filters, QDirIterator::Subdirectories);

			QMultiMap<QDateTime, QString> cacheItems;
			qint64 totalSize = 0;
			while (it.hasNext ())
			{
				const auto& path = it.next ();
				const auto& info = it.fileInfo ();
				cacheItems.insert (info.created (), path);
				totalSize += info.size ();
			}

			auto i = cacheItems.constBegin ();
			while (i != cacheItems.constEnd ())
			{
				if (totalSize < goal)
					break;

				QFile file (*i);
				const auto size = file.size ();
				totalSize -= size;
				++i;

				QMutexLocker lock (fileOpMutex);
				file.remove ();
			}

			qDebug () << "collector finished" << totalSize;

			return totalSize;
		}
	};

	void NetworkDiskCache::collectGarbage ()
	{
		if (IsCollectingGarbage_)
			return;

		if (cacheDirectory ().isEmpty ())
			return;

		IsCollectingGarbage_ = true;

		auto watcher = new QFutureWatcher<qint64> (this);
		connect (watcher,
				SIGNAL (finished ()),
				this,
				SLOT (handleCollectorFinished ()));

		QFuture<qint64> future = QtConcurrent::run (Collector,
				cacheDirectory (), maximumCacheSize () * 9 / 10, &InsertRemoveMutex_);
		watcher->setFuture (future);
	}

	void NetworkDiskCache::handleCollectorFinished ()
	{
		auto watcher = dynamic_cast<QFutureWatcher<qint64>*> (sender ());

		CurrentSize_ = watcher->result ();

		IsCollectingGarbage_ = false;
	}
};

