#include "MonitorLogfile.h"
#include "spdlog/spdlog.h"
#include <QProcess>

void compressLogs()
{
//  SPDLOG_LOGGER_DEBUG(spdlog::get("logger"),"Logfile start compress");
    QString logDirPath = QCoreApplication::applicationDirPath() + "/log";
    QDir logDir(logDirPath);
    // 检查日志目录是否存在
    if (!logDir.exists()) {
        //SPDLOG_LOGGER_DEBUG(spdlog::get("logger"),"Log directory does not exist!");
        return;
    }
    // 获取当前日期，找出昨天的日志文件
    QDate yesterday = QDate::currentDate().addDays(-1);
    QString logFileName = QString("SigerCalculation_%1.log").arg(yesterday.toString("yyyy-MM-dd"));
    QString logFilePath = logDir.filePath(logFileName);

    if (!QFile::exists(logFilePath)) {
        //SPDLOG_LOGGER_DEBUG(spdlog::get("logger"),"Log file {} does not exist",logFilePath);
        return;
    }

    QString CompressLogCommd = QString("sudo gzip -f %1").arg(logFilePath);
    QProcess *CompressProcess = new QProcess();
    CompressProcess->start(CompressLogCommd);
    QString result = CompressProcess->readAllStandardOutput(); // 获取命令的标准输出
    SPDLOG_LOGGER_DEBUG(spdlog::get("logger"),"LogCompress cmd is {}", CompressLogCommd.toStdString());

    return;
}


MonitorLogfile::MonitorLogfile()
{
    // 计算目标时间（每天凌晨 2 点 31）
    QTime targetTime(2, 31, 0);
    QTime currentTime = QTime::currentTime();
    int intervalMs = currentTime.msecsTo(targetTime);

    if (intervalMs <= 0) {
            // 如果当前时间已经过了目标时间，设置为第二天
            intervalMs += 24 * 60 * 60 * 1000;
    }

    // 设置每天定时执行
    if(dailyTimer == nullptr)
    {
        dailyTimer = new QTimer(this);
    }

    QObject::connect(dailyTimer, &QTimer::timeout,this,[&](){
        compressLogs();
        });

    // 定时触发日志打包任务
    QTimer::singleShot(intervalMs, this,[&]() {
        compressLogs();
        dailyTimer->start(24 * 60 * 60 * 1000); // 每天触发一次
    });
}
