#include "netparseprocess.h"
#include "logger.h"
#include "defs.h"
#include "globalsettings.h"

#include <QSettings>
#include <QMetaEnum>

NetParseProcess::NetParseProcess(QObject *parent)
    : QObject{parent}
{
    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("netparse process state: {}, {}", state.toStdString(), error.toStdString());
    });

    // connect(&m_process, &QProcess::readyReadStandardOutput, this, [this](){
    //     QByteArray output = m_process.readAllStandardOutput();
    //     LOG_INFO(output.data());
    // });
}

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

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

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

    QString program = "/usr/bin/python";
    QStringList args;
    args << "/home/forlinx/Desktop/workspace/TPMFM-A/capture_mul.py";
    args << configure;
    args << NETPARSE_FIFO_PATH;

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

    // save netparse configure file path
    GlobalSettings globalSettings;
    globalSettings.setValue("CONFIGURE", "NETPARSE", configure);

    m_process.start(program, args);
}

void NetParseProcess::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 NetParseProcess::restart(const QString &configure)
{
    stop();

    if(configure.isEmpty()) {
        GlobalSettings globalSettings;
        QVariant value = globalSettings.value("CONFIGURE", "CALCULATE");
        if(value.isValid()) {
            start(value.toString());
        } else {
            LOG_INFO("not start netparse process, because not found configure");
        }
    } else {
        start(configure);
    }
    
}

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