//
// Created by uos on 2022/2/24.
//
#include "Process.h"
#include "AsyncTask.h"
#include <QJsonObject>
#include <QDebug>

AsyncTask::AsyncTask()
{

}

AsyncTask::~AsyncTask()
{

}

void AsyncTask::run()
{
    // if (!buildArgumentsForBackup()) {
    //     qCritical() << "build arguments failed";
    //     QJsonObject buildArgsError;
    //     buildArgsError.insert("progress", 0);
    //     buildArgsError.insert("remainSecond", 0);
    //     buildArgsError.insert("errMsg", "build arguments failed");

    //     Q_EMIT error(buildArgsError);
    //     return;
    // }

    if (m_process == nullptr) {
        m_process = new QProcess(this);
        connect(m_process, &QProcess::readyReadStandardOutput, this, &AsyncTask::readStandardOutput, Qt::BlockingQueuedConnection);
        connect(m_process, &QProcess::readyReadStandardError, this, &AsyncTask::readAllStandardError, Qt::BlockingQueuedConnection);
    }

    auto thread = QThread::currentThread();
    m_process->setProgram(m_cmd);
    m_process->setArguments(m_args);
    m_process->setReadChannel(QProcess::StandardOutput);
    m_process->setProcessChannelMode(QProcess::MergedChannels);
    int errCode = -1;
    do {
        m_process->start();
        m_process->waitForFinished(-1);
        m_process->waitForReadyRead(-1);
        errCode = m_process->exitCode();
        if (0 != errCode) {
            QString errString = m_process->errorString();
            // qWarning()<<"failed to run "<<m_cmd<<" "<<m_args<<", tryNum: "<<m_tryNum<<", errString: "<<errString;
        }
    } while ((0 != errCode) && ("rm" == m_cmd) && (m_tryNum-- > 0));
    doResult();
//    m_process->deleteLater();
}

void AsyncTask::setTryNum(int num)
{
    m_tryNum = num;
}

void AsyncTask::readStandardOutput()
{

}

void AsyncTask::readAllStandardError()
{

}

void AsyncTask::kill()
{
    if (nullptr != m_process) {
        m_process->kill();
    }
}
