#include "calprocess.h"
#include "logger.h"
#include "defs.h"

#include <QSettings>
#include <QMetaEnum>

CalProcess::CalProcess(QObject *parent)
{
    // start("/home/forlinx/Desktop/workspace/TPMFM-A/extracted_params20251205.xml", NETPARSE_FIFO_PATH, CALCULATE_FIFO_PATH);

    restart();

    connect(&m_process, &QProcess::stateChanged, this, [this](QProcess::ProcessState newState){
        QString state = QMetaEnum::fromType<QProcess::ProcessState>().valueToKey(newState);
        QString error = QMetaEnum::fromType<QProcess::ProcessError>().valueToKey(m_process.error());
        LOG_INFO("calculate process state: {}, {}", state.toStdString(), error.toStdString());
    });
}

CalProcess::~CalProcess()
{
    stop();
}

void CalProcess::start(const QString &configure)
{
    if (m_process.state() != QProcess::NotRunning) {
        LOG_WARN("netparse is already running!");
        return;
    }

    LOG_INFO("calculate process configure: {}", configure.toStdString());

    QString program = "/usr/bin/python";
    QStringList args;
    args << "/home/forlinx/Desktop/workspace/dataParsing/formula_calculation.py";
    args << configure;
    args << NETPARSE_FIFO_PATH;
    args << CALCULATE_FIFO_PATH;

    LOG_INFO("calculate process args: {}", args.join(" ").toStdString());

    // save formula configure file path
    QSettings settings("storage/conf/settings.ini", QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("CONFIGURE");
    settings.setValue("CALCULATE", configure);
    settings.endGroup();

    m_process.start(program, args);
}

void CalProcess::stop()
{
    if (m_process.state() == QProcess::NotRunning) {
        LOG_INFO("netparse is not running!");
        return;
    }

    LOG_INFO("stopping netparse...");
    m_process.kill();                // 强制终止
    m_process.waitForFinished();     // 等待退出
    LOG_INFO("netparse stopped.");
}

void CalProcess::restart(const QString &configure)
{
    stop();
    if(configure.isEmpty()) {
        QSettings settings("storage/conf/settings.ini", QSettings::IniFormat);
        settings.setIniCodec("UTF-8");
        settings.beginGroup("CONFIGURE");
        if(settings.contains("CALCULATE"))
            start(settings.value("CALCULATE").toString());
        else
            start(configure);
        settings.endGroup();
    } else {
        start(configure);
    }
}

bool CalProcess::isRunning()
{
    return m_process.state() != QProcess::NotRunning;
}
