//
// Created by Krad on 2021/11/19.
//

#include "UserOperationLog.h"
#include <QDate>
#include <QDir>
#include "appvals/AppGlobalValues.h"
#include "models/User.h"
#include <QDirIterator>
#include <qdebug.h>


const char * logDir = "./log";

void UserOperationLog::init() {
    QDir log_dir("./");
    if (!log_dir.exists(logDir)) log_dir.mkdir("log");
    currentFileName = logDir + QDate::currentDate().toString("/yyyy-MM-dd")+QString("-op.log");
    logFile.setFileName(currentFileName);
    if (logFile.exists())
    {
        logFile.open(QFile::OpenModeFlag::Append | QFile::OpenModeFlag::Text);
    } else{
        logFile.open(QFile::OpenModeFlag::NewOnly | QFile::OpenModeFlag::Text);
    }
    out.setDevice(&logFile);
}

const char space = ' ';
QString addSpace(const char* str)
{
    QString s;

    for (int i = 0; str[i]!='\0'; ++i) {
        if (str[i]>='A' && str[i]<='Z' && i>0)
        {
            s.append(space);
            s.append(str[i]);
        } else{
            s.append(str[i]);
        }
    }
    return s;
}


QString getOperationName(UserOperation operation)
{
    switch (operation) {
        #define ADD_OPERATION(name)\
        case name: return addSpace(#name);
        USER_OPERATIONS()
        #undef ADD_OPERATION
        default:
            return "unknow error";
    }

}

void UserOperationLog::log(UserOperation operation, bool processing) {
    reloadFile();
    QDateTime now = QDateTime::currentDateTime();
    AppGlobalValues::setLastOperationTime(now);
    AppGlobalValues::setLastOperation(operation);
    QString operationName = getOperationName(operation);
    AppGlobalValues::setInProcessing(processing);
    QString UserName = (!User::Current() || User::Current()->getUserCode().isEmpty())?"anonymous":User::Current()->getUserCode();
    out << now.toString(Qt::DateFormat::ISODateWithMs).replace("T","\t")<<"\t"<<UserName<<"\t"<<operationName<<endl;
}

void UserOperationLog::reloadFile() {
    QString newFileName = logDir + QDate::currentDate().toString("/yyyy-MM-dd")+QString("-op.log");
    //inprocessing 暂时没有使用
    if (newFileName == currentFileName && !AppGlobalValues::InProcessing().toBool()) return;
    logFile.close();
    logFile.setFileName(newFileName);
    if (logFile.exists())
    {
        logFile.open(QFile::OpenModeFlag::Append | QFile::OpenModeFlag::Text);
    } else{
        logFile.open(QFile::OpenModeFlag::NewOnly | QFile::OpenModeFlag::Text);
    }
    out.setDevice(&logFile);
}

QStringList UserOperationLog::getHistoryLogFiles() {
    QDirIterator iter(logDir, QDir::Files | QDir::NoSymLinks);
    QStringList list;
    while(iter.hasNext())
    {
        iter.next();
        list << iter.fileInfo().absoluteFilePath();
        qDebug()<<iter.fileInfo().absoluteFilePath();
    }
    return list;
}

void UserOperationLog::loadLogFromFile(QString path, QStringList& result) {
    QFile f;
    f.setFileName(path);
    if (!f.exists()) return;
    if(f.open(QFile::OpenModeFlag::ReadOnly | QFile::OpenModeFlag::Text))
    {

        QTextStream in(&f);
        while(!in.atEnd()){
            result << in.readLine();
        }
    }
}
