//
// Created by uos on 2022/6/6.
//
#include "OStreeSystemTest.h"
#include "uos-recovery-service/OSTreeSystem.h"
#include "utils/Utils.h"
#include <QDebug>

OStreeSystemTestHandle::OStreeSystemTestHandle(QEventLoop *eventLoop)
{
    m_eventLoop = eventLoop;
    if (m_ostreeSystem == nullptr) {
        m_ostreeSystem = new OSTreeSystem();
    }

    connect(m_ostreeSystem, &OSTreeSystem::success, this, &OStreeSystemTestHandle::onFinished);
    connect(m_ostreeSystem, &OSTreeSystem::error, this, &OStreeSystemTestHandle::onFinished);
    connect(m_ostreeSystem, &OSTreeSystem::progressChanged, this, &OStreeSystemTestHandle::onProgressChanged);
}

void OStreeSystemTestHandle::systemBackup()
{
    SystemBackupRequest req;
    req.rootUUID = "3da86cc7-7814-4258-9f70-cc50a5d1a110";
    req.destUUID = "3da86cc7-7814-4258-9f70-cc50a5d1a110";

    ErrorCode retCode = m_ostreeSystem->systemBackup(req);
    if (ErrorCode::OK != retCode) {
        onFinished("call systemBackup failed, exit now!");
    }
    EXPECT_TRUE(ErrorCode::OK == retCode);
}

void OStreeSystemTestHandle::querySubject()
{
    QStringList noUUID;
    BackupInfoList backupInfoList = m_ostreeSystem->listSystemBackup(noUUID);
    if (backupInfoList.isEmpty()) {
        qInfo()<< Q_FUNC_INFO << "listSystemBackup faield";
    }
}

void OStreeSystemTestHandle::removeBackup()
{
    /*
     * ['v23.1.3.20220610',
        'v23.1.2.20220610',
        'v23.1.1.20220610',
        'v23.1.0.20220610',
         'v23.0.0.20220607']
     */
    RemoveUserDataBackupRequest req;
    req.backupInfo.submissionVersion = "v23.1.1.20220610";
    ErrorCode retCode = m_ostreeSystem->removeSystemBackup(req);
    if (ErrorCode::OK != retCode) {
        onFinished("call removeSystemBackup failed, exit now!");
    }
    EXPECT_TRUE(ErrorCode::OK == retCode);
}

void OStreeSystemTestHandle::onProgressChanged(const QString &progress)
{
    QJsonObject progressJson = Utils::QStringToJson(progress);
    if (!progressJson.contains("OStreeOperate")) {
        return;
    }

    if (progressJson.contains("progress")) {
        int curProgress = progressJson.value("progress").toInt();
        qInfo()<<Q_FUNC_INFO<<", curProgress = "<<curProgress;
        if (curProgress >= 100) {
            onFinished(progress);
            return;
        }
    }
}

void OStreeSystemTestHandle::onFinished(const QString &msg)
{
    if (nullptr != m_ostreeSystem) {
        delete m_ostreeSystem;
        m_ostreeSystem = nullptr;
    }

    m_eventLoop->quit();
}


TEST_F(OStreeSystemTest, commit)
{
    m_taskHandle->systemBackup();

    m_loop->exec();
}

TEST_F(OStreeSystemTest, querySubject)
{
    m_taskHandle->querySubject();
}

TEST_F(OStreeSystemTest, delete)
{
    m_taskHandle->removeBackup();
    m_loop->exec();
}
