/**********************************************************************
 * 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 "msgtemplatesmanager.h"
#include <functional>
#include <QLocale>
#include <QtDebug>
#include <interfaces/itexteditor.h>
#include <util/sll/either.h>
#include <util/sll/monadplus.h>
#include <util/sll/curry.h>
#include <util/sys/paths.h>
#include <util/util.h>
#include "message.h"
#include "account.h"
#include "structures.h"
#include "templatesstorage.h"
#include "templatepattern.h"

namespace LeechCraft
{
namespace Snails
{
	MsgTemplatesManager::MsgTemplatesManager (QObject *parent)
	: QObject { parent }
	, Storage_ { std::make_shared<TemplatesStorage> () }
	{
	}

	auto MsgTemplatesManager::GetTemplate (ContentType contentType,
			MsgType msgType, const Account *account) const -> LoadResult_t
	{
		static const auto defaults = GetDefaults ();

		return [&] (const auto& maybeResult)
					{ return maybeResult ? *maybeResult : defaults [contentType] [msgType]; } *
				(
					Util::Pure<TemplatesStorage::LoadResult_t> (Util::Mplus) *
							Storage_->LoadTemplate (contentType, msgType, account) *
							Storage_->LoadTemplate (contentType, msgType, nullptr)
				);
	}

	namespace
	{
		static const QString OpenMarker = "${";
		static const QString CloseMarker = "}";

		QString PerformSubstitutions (const Account *acc,
				const Message *msg, ContentType type, const QString& body, QString text)
		{
			const auto functions = GetKnownPatternsHash ();

			const auto openSize = OpenMarker.size ();

			auto pos = 0;
			while ((pos = text.indexOf (OpenMarker, pos)) != -1)
			{
				const auto closing = text.indexOf (CloseMarker, pos);
				if (closing == -1)
					break;

				const auto& variable = text.mid (pos + openSize, closing - pos - openSize);

				if (functions.contains (variable))
				{
					const auto& subst = functions [variable] (acc, msg, type, body);
					text.replace (pos, closing - pos + 1, subst);
					pos += subst.size ();
				}
				else
					pos = closing + 1;
			}

			return text;
		}
	}

	QString MsgTemplatesManager::GetTemplatedText (ContentType type,
			MsgType msgType, const Account *acc, const QString& body, const Message *msg) const
	{
		return Util::RightOr (Util::Curry (&PerformSubstitutions) (acc) (msg) (type) (body) *
					GetTemplate (type, msgType, acc),
				body);
	}

	auto MsgTemplatesManager::SaveTemplate (ContentType type,
			MsgType msgType, const Account *acc, const QString& tpl) -> SaveResult_t
	{
		return Storage_->SaveTemplate (type, msgType, acc, tpl);
	}

	namespace
	{
		QString LoadTemplate (ContentType ct, MsgType msgType)
		{
			const auto& basename = GetBasename (msgType);
			const auto& extension = GetExtension (ct);
			const auto& mkFilename = [&] (const QString& locale)
			{
				return basename + (locale.isEmpty () ? "" : ("_" + locale)) + "." + extension;
			};

			const auto& localeName = Util::GetLocaleName ();

			auto str = Util::GetSysPath (Util::SysPath::Share,
					"snails/templates", mkFilename (localeName.left (2)));
			if (str.isEmpty ())
				str = Util::GetSysPath (Util::SysPath::Share,
						"snails/templates", mkFilename ({}));
			if (str.isEmpty ())
				return {};

			QFile file { str };
			if (!file.open (QIODevice::ReadOnly))
			{
				qWarning () << Q_FUNC_INFO
						<< "unable to open file"
						<< file.fileName ()
						<< file.errorString ();
				return {};
			}

			auto data = file.readAll ();
			if (ct == ContentType::HTML)
				data.replace ('\n', "");
			return QString::fromUtf8 (data);
		}
	}

	QMap<ContentType, QMap<MsgType, QString>> MsgTemplatesManager::GetDefaults ()
	{
		QMap<ContentType, QMap<MsgType, QString>> result;
		for (auto ct : { ContentType::PlainText, ContentType::HTML })
			for (auto msgType : { MsgType::New, MsgType::Reply, MsgType::Forward })
				result [ct] [msgType] = LoadTemplate (ct, msgType);
		return result;
	}
}
}
