/**********************************************************************
 * 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.
 **********************************************************************/

#pragma once

#include <boost/variant.hpp>
#include <QObject>
#include <vmime/net/session.hpp>
#include <vmime/net/message.hpp>
#include <vmime/net/folder.hpp>
#include <vmime/net/store.hpp>
#include <vmime/security/cert/certificateVerifier.hpp>
#include <util/sll/assoccache.h>
#include <util/sll/either.h>
#include <interfaces/structures.h>
#include "progresslistener.h"
#include "messageinfo.h"
#include "account.h"
#include "accountthreadworkerfwd.h"

class QTimer;

namespace LeechCraft
{
namespace Snails
{
	class Account;
	class Storage;
	class MessageChangeListener;

	template<typename T>
	class AccountThreadNotifier;

	struct Folder;

	struct OutgoingMessage;

	using MessageVector_t = std::vector<vmime::shared_ptr<vmime::net::message>>;
	using VmimeFolder_ptr = vmime::shared_ptr<vmime::net::folder>;
	using CertList_t = std::vector<vmime::shared_ptr<vmime::security::cert::X509Certificate>>;

	class AccountThreadWorker : public QObject
	{
		Account * const A_;
		Storage * const Storage_;

		QTimer * const NoopTimer_;

		const bool IsListening_;

		const QString ThreadName_;

		MessageChangeListener * const ChangeListener_;

		vmime::shared_ptr<vmime::net::session> Session_;
		vmime::shared_ptr<vmime::net::store> CachedStore_;

		Util::AssocCache<QStringList, vmime::shared_ptr<vmime::net::folder>> CachedFolders_;

		const vmime::shared_ptr<vmime::security::cert::certificateVerifier> CertVerifier_;
		const vmime::shared_ptr<vmime::security::authenticator> InAuth_;

		enum class FolderMode
		{
			ReadOnly,
			ReadWrite,
			NoChange
		};
	public:
		AccountThreadWorker (bool, const QString&, Account*, Storage*);

		using Folder2Messages_t = QHash<QStringList, QList<FetchedMessageInfo>>;

		struct SyncStatusesResult
		{
			QList<QByteArray> RemovedIds_;

			QList<QByteArray> RemoteBecameRead_;
			QList<QByteArray> RemoteBecameUnread_;
		};
	private:
		vmime::shared_ptr<vmime::net::store> MakeStore ();
		vmime::shared_ptr<vmime::net::transport> MakeTransport ();

		VmimeFolder_ptr GetFolder (const QStringList& folder, FolderMode mode);

		FetchedMessageInfo FromHeaders (const vmime::shared_ptr<vmime::net::message>&) const;

		QList<FetchedMessageInfo> FetchMessagesInFolder (const QStringList&, const VmimeFolder_ptr&, const QByteArray&);

		SyncStatusesResult SyncMessagesStatusesImpl (const QStringList&, const VmimeFolder_ptr&);

		void SetNoopTimeout (int);
		void SendNoop ();
	public:
		void SetNoopTimeoutChangeNotifier (const std::shared_ptr<AccountThreadNotifier<int>>&);

		void Disconnect ();

		void TestConnectivity ();

		struct SyncResult
		{
			Folder2Messages_t Messages_;
		};
		QList<Folder> SyncFolders ();
		SyncResult Synchronize (const QList<QStringList>&, const QByteArray& last);

		SyncStatusesResult SyncMessagesStatuses (const QStringList&);

		using MsgCountError_t = boost::variant<FolderNotFound>;
		using MsgCountResult_t = Util::Either<MsgCountError_t, QPair<int, int>>;
		MsgCountResult_t GetMessageCount (const QStringList& folder);

		using SetReadStatusResult_t = Util::Either<boost::variant<FolderNotFound>, Util::Void>;
		SetReadStatusResult_t SetReadStatus (bool read, const QList<QByteArray>& ids, const QStringList& folder);

		FetchWholeMessageResult_t FetchWholeMessage (const QStringList& folder, const QByteArray& msgId);

		FetchAttachmentResult_t FetchAttachment (const QStringList& folder,
				const QByteArray& msgId, const QString& attName, const QString& path);

		void CopyMessages (const QList<QByteArray>& ids, const QStringList& from, const QList<QStringList>& tos);

		using DeleteResult_t = Util::Either<boost::variant<FolderNotFound>, Util::Void>;
		DeleteResult_t DeleteMessages (const QList<QByteArray>& ids, const QStringList& folder);

		void SendMessage (const OutgoingMessage&);
	};
}
}
