//
// Created by xin on 2021/8/17.
//edit by zz.
//fixed code page problem;added a new initialize function; --20211101
#pragma once

#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include "qmutex.h"
#include "QtMsgHandler"

namespace QT_LOG
{
    static int m_LogLevel = 1;
    static QString m_LogFile = QString("%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
    QMutex m_LogMutex;

    void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
    {
        if (type < m_LogLevel)
        {
            return;
        }

        QString log_info;
        switch (type)
        {
            case QtDebugMsg:
                log_info = QString("%1:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg);
                break;

            case QtWarningMsg:
                log_info = QString("%1[Warning]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg);
                break;

            case QtCriticalMsg:
                log_info = QString("%1[Critical]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg);
                break;

            case QtFatalMsg:
                log_info = QString("%1[Fatal]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg);
                abort();
        }

        m_LogMutex.lock();

        QFile outFile(m_LogFile);
        outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
        QTextStream ts(&outFile);
        ts << log_info << endl;

        std::cout<<log_info.toStdString()<<std::endl;

        outFile.close();

        m_LogMutex.unlock();
    }
    void logInit(QString logFile = "",int logLevel = 0)
    {

#ifndef _Debug
        if ((logLevel < 0) || (logLevel > 3))
        {
            m_LogLevel = 1;
        }
        else
        {
            m_LogLevel = logLevel;
        }

        if (!logFile.isEmpty())
        {
            m_LogFile = logFile+"/"+m_LogFile;
        }

        qInstallMessageHandler(customMessageHandler);
        //qInstallMsgHandler(customMessageHandler);
#endif
    }

	//added by IRIS_ZZ initialize from main 
	void ZZ_InitLogger(QString qstrDir)
	{
		QDir qdLogFolder;
		qdLogFolder.mkdir(qstrDir);
		qDebug() << QT_LOG::m_LogFile;
		QT_LOG::logInit(qstrDir);
	}
};



