//
// Created by uos on 2022/5/23.
//

#include "RemoveTask.h"
#include "utils/global.h"
#include "utils/Utils.h"
#include "utils/Device.h"
#include <QDebug>
#include <QJsonObject>
#include <QDir>

RemoveTask::RemoveTask()
{

}

ErrorCode RemoveTask::remove(const BackupInfo &backupInfo)
{
    this->setTryNum(1);
    if (OperateType::GhostBackup == static_cast<OperateType>(backupInfo.operateType)) {
        return this->removeGhostDir(backupInfo);
    }

    m_delBackupInfo = backupInfo;
    ErrorCode errorCode = OK;
    if (backupInfo.recoveryType == static_cast<int>(RecoveryType::Rsync)) {
        if (backupInfo.backupDevUUID.isEmpty()) {
            qCritical() << "error: backupDevUUID isEmpty";
            return ErrorCode::DestUuidIsEmpty;
        }

        QString mountPoint;
        if (!Device::getMountPointByUUID(backupInfo.backupDevUUID, mountPoint)) {
            qCritical() << "getMountPointByUUID failed, backupDevUUID = "<< backupInfo.backupDevUUID;
            return PartitionNotMount;
        }
        m_cmd = "rm";
        QDir dir(mountPoint + backupInfo.backupPath);
        dir.cdUp();
        if (dir.exists()) {
            m_args << "-rf" << dir.absolutePath();
            this->start();
        } else {
            Q_EMIT success(QJsonObject());
        }
    }
    return errorCode;
}

ErrorCode RemoveTask::removeGhostDir(const BackupInfo &backupInfo)
{
    ErrorCode errorCode = OK;
    QString path;
    if (backupInfo.backupDeviceRemovable) {
        QString mountPoint;
        Device::getMountPointByUUID(backupInfo.backupDevUUID, mountPoint);
        path = mountPoint + backupInfo.backupPath;
    } else {
        path = backupInfo.backupPath;
    }

    m_cmd = "rm";
    QDir dir(path);
    if (dir.exists()) {
        m_args << "-rf" << dir.absolutePath();
        // qWarning()<<"delete uimg temp dir: "<<dir.absolutePath();
        this->start();
    } else {
        // qWarning()<<"not exist uimg temp dir: "<<path;
        Q_EMIT success(QJsonObject());
    }
    return errorCode;
}

void RemoveTask::readStandardOutput()
{

}

void RemoveTask::readAllStandardError()
{

}

void RemoveTask::doResult()
{
    QJsonObject jsonObject;
    QString err = m_process->readAllStandardError();
    int errCode = m_process->exitCode();

    if (m_process->exitStatus() != QProcess::NormalExit || errCode != 0) {
        QProcess::ProcessError pError = m_process->error();
        QString errStr = m_process->errorString();
        qCritical()<<"RemoveTask::run, errCode = "<<errCode<<", pError: "<<pError<<", errStr: "<<errStr;
        // qCritical() << QString("exec %1 failed, arguments:%2").arg(m_cmd).arg(m_args.join(" "));
        qCritical() << err;
        Q_EMIT error(jsonObject);
        return;
    }
    Q_EMIT success(jsonObject);
}

bool RemoveTask::buildArgumentsForBackup()
{
    return true;
}

bool RemoveTask::buildArgumentsForRestore(const QString &fromDir)
{
    return true;
}
