#include "Logger.h"

#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>

namespace
{
constexpr int logFileSize = 5 * 1024 * 1024;
const int logFileCount = 10;
QFile logFile;

QString logFileName()
{
	QList<QFileInfo> fileInfos;
	for (int i = 0; i < logFileCount; ++i)
	{
		const auto fileName = QString("logs/log_%1.txt").arg(i);
		const QFileInfo info(fileName);
		if (!info.exists())
		{
			return fileName;
		}

		fileInfos.append(info);
	}

	QFile::remove(fileInfos.first().filePath());
	for (int i = 0; i < logFileCount - 1; ++i)
	{
		QFile::rename(fileInfos[i + 1].filePath(), fileInfos[i].filePath());
	}

	return fileInfos.last().filePath();
}

void checkLogFile()
{
	if (!logFile.isOpen())
	{
		if (!QFile::exists("logs"))
		{
			QDir().mkdir("logs");
		}

		logFile.setFileName(logFileName());
		logFile.open(QIODevice::WriteOnly);
	}
	else if (logFile.size() > logFileSize)
	{
		logFile.close();
		logFile.setFileName(logFileName());
		logFile.open(QIODevice::WriteOnly);
	}
}
}

QString logMessagePattern()
{
	return "[%{time yyyy-MM-dd hh:mm:ss.zzz}] %{message}";
}

void logMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
	QString message = qFormatLogMessage(type, context, msg);

	checkLogFile();
	logFile.write(message.toUtf8() + "\n");

	QTextStream out(stdout);
	out << message << Qt::endl;
}
