#include "logger.h"

#include <QThread>

Logger::Logger()
{
    connect(this,&Logger::sigAddToLogger, this, &Logger::handleLog,Qt::AutoConnection);
    createDirectory();
}

Logger &Logger::instance()
{
    static Logger logger;
    return logger;
}

Logger::~Logger()
{

}

void Logger::setLoggingType(LoggingType type)
{
    this->loggingType = type;
}

void Logger::log(QString message, LogLevel level)
{
    emit sigAddToLogger(message,level);
}

void Logger::setLogFile(QString filePath)
{
    QMutexLocker locker(&mutex);
    if (logFile.isOpen())
    {
        logFile.close();
    }

    logFile.setFileName(filePath);
    logFile.open(QIODevice::WriteOnly | QIODevice::Append);
}

void Logger::setLogToFile(bool flag)
{
    isLogToFile = flag;
    if (flag)
    {
        QString filePath = logFolderPath + "/" + "log " + QDateTime::currentDateTime().toString("dd-MM-yyyy")+".txt";
        setLogFile(filePath);
    }
}

void Logger::handleLog(QString msg, LogLevel logLevel)
{
    QString level;

    switch (logLevel)
    {
        case INFO: level = "INFO"; break;
        case WARNING: level = "WARNING"; break;
        case ERROR: level = "ERROR"; break;
        case CRITICAL: level = "CRITICAL"; break;
        case DEBUG: level = "DEBUG"; break;
    }

    QString timeStamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString message = timeStamp + " " + level + " " + msg;


    if (loggingType == LoggingType::WIDGET)
    {
        emit sigLogToWidget(message);
    }
    else if(loggingType == LoggingType::CONSOLE)
    {
        qDebug() << message;
    }

    if(isLogToFile)
    {
        QMutexLocker locker(&mutex);
        if (logFile.isOpen())
        {
            QTextStream stream(&logFile);
            stream << message << "\n";
        }
    }
}

void Logger::createDirectory()
{
    QString directoryPath = logFolderPath;
    QDir dir(directoryPath);

    if(!dir.exists()) dir.mkdir(".");

}
