#include "applog.h"
#include <QMutex>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDate>
#include <QApplication>

QtMessageHandler messageHandler = NULL;

AppLog::AppLog()
{

}

AppLog::~AppLog()
{

}

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug");
        break;
    case QtInfoMsg:
        text = QString("Info");
        break;
    case QtWarningMsg:
        text = QString("Warning");
        break;
    case QtCriticalMsg:
        text = QString("Critical");
        break;
    case QtFatalMsg:
        text = QString("Fatal");
    }
    QString context_info = QString("File:(%1) Line:(%2) Function:%3")
            .arg(QString(context.file))
            .arg(context.line)
            .arg(context.function);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3").arg(context_info).arg(msg).arg(current_date);

    //加锁
    static QMutex applog_mutex;
    applog_mutex.lock();

    //输出信息至文件中（读写、追加形式）
    //    QString logFileDir = QString("%1/log/%2")
    //            .arg(QApplication::applicationDirPath())
    //            .arg(QDate::currentDate().toString("yyyy-MM-dd"));
    QString logFileDir = QString("%1/log")
            .arg(QApplication::applicationDirPath());
    //    QString logFileName = QString("%1_%2_log.txt")
    //            .arg(QApplication::applicationName())
    //            .arg(text);
    QString logFileName = QString("%1_%2_%3_log.txt")
            .arg(QApplication::applicationName())
            .arg(text)
            .arg(QDate::currentDate().toString("yyyy-MM-dd"));

    QDir logDir(logFileDir);
    if (!logDir.exists())
        logDir.mkpath(logFileDir);

    QFile file(QString("%1/%2").arg(logFileDir).arg(logFileName));
    file.open(QIODevice::WriteOnly | QIODevice::Append | QFile::Text);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();
    //解锁
    applog_mutex.unlock();

    //用系统原来的函数完成原来的功能. 比如输出到调试窗
    if (messageHandler)
        messageHandler(type, context, msg);
}

void AppLog::start()
{
    //安装日志钩子
    messageHandler = qInstallMessageHandler(outputMessage);
}

void AppLog::stop()
{
    //卸载日志钩子
    qInstallMessageHandler(0);
}

void AppLog::onClearLogFile(QString path, int keepLogDays)
{
    QStringList fileList;
    //需要清理文件的类型
    QStringList filterList;
    QString fileType = "*.txt";
    filterList.append(fileType);
    //获取目录内的文件列表
    QDir dir = QDir(path);
    Q_ASSERT(dir.exists());
    fileList = dir.entryList(filterList, QDir::Files, QDir::Name);
    QDateTime currDt = QDateTime::currentDateTime();
    foreach (QString fileName, fileList)
    {
        //获取文件的创建时间
        QFileInfo info(path + "/" + fileName);
        QDateTime dt = info.created();
        int days = dt.daysTo(currDt);
        if(days > keepLogDays)
        {
            QFile::remove(path + "/" + fileName);
        }
    }
}

bool RemoveDir(QString dirPath)
{
    if(dirPath.isEmpty())
        return false;
    QDir dir(dirPath);
    if(!dir.exists())
        return true;
    for(QFileInfo info:dir.entryInfoList())
    {

        if(info.isFile())
        {
            QFile::remove(info.filePath());
        }
        else
        {
            RemoveDir(info.absoluteFilePath());
        }
    }

    return dir.remove(dir.absolutePath());
}


