// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2015 Konrad Twardowski

#include "log.h"

#ifdef Q_OS_LINUX
	#include <unistd.h>
#endif

#include <QDateTime>
#include <QLoggingCategory>

// public:

void Log::error(const QString &text) {
	log("ERROR", text);
}

void Log::info(const QString &text) {
	log("INFO", text);
}

void Log::init() {
/* TODO: ?
	qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context, const QString &msg) {
		fprintf(stderr, msg.
	});
*/

	#ifdef Q_OS_LINUX
	terminal = ::isatty(fileno(stderr)) == 1;
	#endif

// TODO: logging options
	QLoggingCategory::setFilterRules("default=true");

	QString debugPattern   = "%{if-debug}"    + makeColor(36, "debug")       + "%{endif}";
	QString fatalPattern   = "%{if-fatal}"    + makeColor(31, "FATAL ERROR") + "%{endif}";
	QString infoPattern    = "%{if-info}"     + makeColor(34, "info")        + "%{endif}";
	QString errorPattern   = "%{if-critical}" + makeColor(31, "error")       + "%{endif}";
	QString warningPattern = "%{if-warning}"  + makeColor(35, "warning")     + "%{endif}";

	qSetMessagePattern(
		"kshutdown %{time yyyy-MM-dd hh:mm:ss} %{if-category}" + makeColor(32, "%{category}") + "/%{endif}" +
		debugPattern + errorPattern + fatalPattern + infoPattern + warningPattern +
		": %{message}"
	);
/* TEST:
	QLoggingCategory testCategory("test");
	qCDebug(testCategory, "Category test");

	qDebug() << "Debug test";
	qCritical() << "Error test";
	qInfo() << "Information test";
	qWarning() << "Warning test";
	qFatal("Fatal test");
*/

// TODO: use QMessageLogger #5.x
/*
	logFile = new QFile("log.txt");

	if (logFile->exists()) {
		logFile->copy("log-previous.txt");
	}

	if (logFile->open(QFile::Truncate | QFile::WriteOnly)) {
		output = new QTextStream(logFile);
		output->setCodec("UTF-8");

		info("KShutdown Startup");
	}
*/
}

void Log::shutDown() {
	if (output != nullptr) {
		info("KShutdown Exit");

		delete output; // flush
		output = nullptr;
	}
}

void Log::warning(const QString &text) {
	log("WARNING", text);
}

// private:

void Log::log(const QString &category, const QString &text) {
	if (output != nullptr) {
		auto now = QDateTime::currentDateTime();
		*output << (now.toString(Qt::ISODate) + "  " + category + ": " + text + '\n');
		output->flush();
	}
}

QString Log::makeColor(const int color, const QString &text) {
	if (terminal)
		return "\033[" + QString::number(color) + 'm' + text + "\033[0m";

	return text;
}
