/**********************************************************************
 * 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 "deltastorage.h"
#include <stdexcept>
#include <algorithm>
#include <QFile>
#include <QVector>
#include <QCoreApplication>
#include <util/util.h>
#include <util/sync/syncops.h>

namespace LeechCraft
{
	namespace Plugins
	{
		namespace SeekThru
		{
			DeltaStorage::DeltaStorage (const QString& id, QObject *parent)
			: QObject (parent)
			, ID_ (id)
			, Settings_ (QCoreApplication::organizationName (),
					QCoreApplication::applicationName ())
			{
				Settings_.beginGroup ("DeltaStorage");
				Settings_.beginGroup (id);
			}

			DeltaStorage::~DeltaStorage ()
			{
				Settings_.endGroup ();
				Settings_.endGroup ();
			}

			void DeltaStorage::Store (const Sync::ChainID_t& chainId, const Sync::Payload& payload)
			{
				Settings_.beginGroup (chainId);
				bool shouldStore = Settings_.value ("EverRequested", false).toBool ();
				Settings_.endGroup ();
				if (!shouldStore)
					return;

				QDir dir = GetDir (chainId);
				int curNum = GetLastFileNum (chainId) + 1;

				StoreImpl (dir.absoluteFilePath (QString::number (curNum)), payload);

				SetLastFileNum (chainId, curNum);
			}

			void DeltaStorage::Store (const Sync::ChainID_t& chainId, const Sync::Payloads_t& payloads)
			{
				Settings_.beginGroup (chainId);
				bool shouldStore = Settings_.value ("EverRequested", false).toBool ();
				Settings_.endGroup ();
				if (!shouldStore)
					return;

				QDir dir = GetDir (chainId);
				int curNum = GetLastFileNum (chainId);

				Q_FOREACH (const Sync::Payload& payload, payloads)
					StoreImpl (dir.absoluteFilePath (QString::number (++curNum)), payload);

				SetLastFileNum (chainId, curNum);
			}

			Sync::Payloads_t DeltaStorage::Get (const Sync::ChainID_t& chainId)
			{
				DeltasRequested (chainId);

				QMap<int, Sync::Payload> tmpPayloads;

				QDir dir = GetDir (chainId);

				Q_FOREACH (const QString& filename, dir.entryList (QDir::Files | QDir::NoDotAndDotDot))
				{
					bool ok = true;
					int num = filename.toInt (&ok);
					if (!ok)
						continue;

					QFile file (dir.absoluteFilePath (filename));
					if (!file.open (QIODevice::ReadOnly))
					{
						qWarning () << Q_FUNC_INFO
								<< "unable to open"
								<< file.fileName ()
								<< "for reading:"
								<< file.errorString ();
						throw std::runtime_error ("Unable to open file for reading.");
					}

					QByteArray data = file.readAll ();
					Sync::Payload payload = Sync::Deserialize (qUncompress (data));
					tmpPayloads [num] = payload;
				}

				QList<Sync::Payload> result;
				QList<int> keys = tmpPayloads.keys ();
				std::sort (keys.begin (), keys.end ());
				Q_FOREACH (int key, keys)
					result << tmpPayloads [key];

				return result;
			}

			void DeltaStorage::Purge (const Sync::ChainID_t& chainId, quint32 num)
			{
				QDir dir = GetDir (chainId);
				quint32 purged = 0;
				Q_FOREACH (const QString& filename, dir.entryList (QDir::Files | QDir::NoDotAndDotDot))
				{
					if (!dir.remove (filename))
						qWarning () << Q_FUNC_INFO
								<< "could not remove"
								<< filename;
					if (++purged == num)
						break;
				}
			}

			void DeltaStorage::DeltasRequested (const Sync::ChainID_t& chainId)
			{
				Settings_.beginGroup (chainId);
				Settings_.setValue ("EverRequested", true);
				Settings_.endGroup ();
			}

			QDir DeltaStorage::GetDir (const Sync::ChainID_t& chainId) const
			{
				return Util::CreateIfNotExists ("deltastorage/" + ID_ + "/" + chainId);
			}

			int DeltaStorage::GetLastFileNum (const Sync::ChainID_t& chainId)
			{
				Settings_.beginGroup (chainId);
				int num = Settings_.value ("LastFileNum", 0).toInt ();
				Settings_.endGroup ();
				return num;
			}

			void DeltaStorage::SetLastFileNum (const Sync::ChainID_t& chainId, int num)
			{
				Settings_.beginGroup (chainId);
				Settings_.setValue ("LastFileNum", num);
				Settings_.endGroup ();
			}

			void DeltaStorage::StoreImpl (const QString& path, const Sync::Payload& payload)
			{
				QFile file (path);
				if (!file.open (QIODevice::WriteOnly))
				{
					qWarning () << Q_FUNC_INFO
							<< "unable to open file"
							<< file.fileName ()
							<< "for writing:"
							<< file.errorString ();
					throw std::runtime_error ("Unable to open file for writing.");
				}

				file.write (qCompress (Sync::Serialize (payload), 5));
			}
		}
	}
}
