/**********************************************************************
 * 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 "clientloggermanager.h"
#include <QDir>
#include <QXmppClient.h>
#include <QXmppLogger.h>
#include <util/sys/paths.h>
#include "accountsettingsholder.h"
#include "clientconnection.h"

namespace LC::Azoth::Xoox
{
	ClientLoggerManager::ClientLoggerManager (QXmppClient& client, AccountSettingsHolder& settings, QObject *parent)
	: QObject { parent }
	, FileLogSink_ { new QXmppLogger { this } }
	{
		QFile::remove (Util::CreateIfNotExists ("azoth").filePath ("qxmpp.log"));

		auto [jid, bare] = ClientConnection::Split (settings.GetFullJID ());
		QString logName = jid + ".qxmpp.log";
		logName.replace ('@', '_');
		const QString& path = Util::CreateIfNotExists ("azoth/xoox/logs").filePath (logName);
		QFileInfo info (path);
		if (info.size () > 1024 * 1024 * 10)
			QFile::remove (path);

		const auto logger = new QXmppLogger { this };
		logger->setLoggingType (QXmppLogger::SignalLogging);
		logger->setMessageTypes (QXmppLogger::AnyMessage);
		connect (logger,
				&QXmppLogger::message,
				this,
				[this] (QXmppLogger::MessageType type, const QString& msg)
				{
					const auto& curPath = FileLogSink_->logFilePath ();
					if (!QFile::exists (curPath))
						FileLogSink_->reopen ();
					FileLogSink_->log (type, msg);

					if (Signaled_)
						EmitConsoleLog (type, msg);
				});
		client.setLogger (logger);

		FileLogSink_->setLogFilePath (path);
		FileLogSink_->setMessageTypes (QXmppLogger::AnyMessage);

		auto setFileLogging = [this] (bool fileLog)
		{
			FileLogSink_->setLoggingType (fileLog ? QXmppLogger::FileLogging : QXmppLogger::NoLogging);
		};
		connect (&settings,
				&AccountSettingsHolder::fileLogChanged,
				this,
				setFileLogging);
		setFileLogging (settings.GetFileLogEnabled ());
	}

	void ClientLoggerManager::SetSignaledLog (bool signaled)
	{
		Signaled_ = signaled;
	}

	void ClientLoggerManager::EmitConsoleLog (QXmppLogger::MessageType type, const QString& msg)
	{
		QString entryId;
		QDomDocument doc;
		if (doc.setContent (msg))
		{
			const auto& elem = doc.documentElement ();
			if (type == QXmppLogger::ReceivedMessage)
				entryId = elem.attribute ("from");
			else if (type == QXmppLogger::SentMessage)
				entryId = elem.attribute ("to");
		}

		switch (type)
		{
		case QXmppLogger::SentMessage:
			emit gotConsoleLog (msg.toUtf8 (), IHaveConsole::PacketDirection::Out, entryId);
			break;
		case QXmppLogger::ReceivedMessage:
			emit gotConsoleLog (msg.toUtf8 (), IHaveConsole::PacketDirection::In, entryId);
			break;
		default:
			break;
		}
	}

}
