#include "DLog.h"
#include <QtDebug>

#define DEBUG_FILE_NAME  "debug.txt"
#define DEBUG_FILE_BACKUP  "debug_bak.txt"
#define DEBUG_FILE_MAX_SIZE (1*1024*1024)  //1MB

void DLog_Init()
{

    QDir dir("D:/tmp");

    if(dir.exists()){
        //clear tmp
        dir.setFilter(QDir::Files);

        int filecount = dir.count();
        for(int i=0; i< filecount; i++){
            dir.remove(dir[i]);
        }

        qDebug() << "D:/tmp is exists";

    }else{

        dir.mkdir("D:/tmp");
        qDebug() << "D:/tmp is not exists, mk it";
    }


    QFile file(DEBUG_FILE_NAME);
    if( file.exists() && file.size() >= DEBUG_FILE_MAX_SIZE ){

        {
            QFile file_bak(DEBUG_FILE_BACKUP);
            if(file_bak.exists()){
                file_bak.remove();
            }
        }

        file.rename(DEBUG_FILE_BACKUP);

    }

    //qInstallMessageHandler(myMsgOutput);


}

void myMsgOutput(QtMsgType type, const QMessageLogContext &context, const QString& msg)
{
    static QMutex mutex;
    mutex.lock();
    QString time=QDateTime::currentDateTime().toString(QString("[ yyyy-MM-dd HH:mm:ss:zzz ]"));
    QString mmsg;
    switch(type)
    {
    case QtDebugMsg:
        mmsg=QString("%1: Debug:\t%2 (file:%3, line:%4, func: %5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtInfoMsg:
        mmsg=QString("%1: Info:\t%2 (file:%3, line:%4, func: %5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtWarningMsg:
        mmsg=QString("%1: Warning:\t%2 (file:%3, line:%4, func: %5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtCriticalMsg:
        mmsg=QString("%1: Critical:\t%2 (file:%3, line:%4, func: %5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtFatalMsg:
        mmsg=QString("%1: Fatal:\t%2 (file:%3, line:%4, func: %5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        abort();
    }

    QFile file(DEBUG_FILE_NAME);
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << mmsg << "\r\n";
    file.flush();
    file.close();
    mutex.unlock();
}
