//
// Created by dtx on 2022/3/23.
//

#include "MakeSquashfsTaskTest.h"
#include "utils/Process.h"
#include <QDebug>
#include <QDir>
#include "stdio.h"


MakeSquashfsTaskTestHandle::MakeSquashfsTaskTestHandle(QEventLoop *eventLoop)
{
    m_squashfsTask = new SquashfsTask();
    m_eventLoop = eventLoop;
}

MakeSquashfsTaskTestHandle::~MakeSquashfsTaskTestHandle()
{
    if (m_squashfsTask != nullptr) {
        delete m_squashfsTask;
        m_squashfsTask = nullptr;
    }
}

bool MakeSquashfsTaskTestHandle::doMakeSquashfs(const QString &srcdir, const QString &destfile)
{
    // 压缩文件
    QString distfiletmp = srcdir + "/squashfsfiletest.txt";
    FILE *fp = nullptr;
    fp = fopen(distfiletmp.toStdString().c_str(), "wb+");
    if (fp != nullptr) {
        QString teststr = "";
        for(int i = 0; i < 1024; i++)
            teststr += QString("-%1-").arg(i);
        qInfo() << "teststr size : "<< teststr.length();
        for(int i = 0; i < 1024; i++) {
            fwrite(teststr.toStdString().c_str(), teststr.length(), 1024*1024, fp);
            fwrite(teststr.toStdString().c_str(), teststr.length(), 1024*1024, fp);
            fwrite(teststr.toStdString().c_str(), teststr.length(), 1024*1024, fp);
            fwrite(teststr.toStdString().c_str(), teststr.length(), 1024*1024, fp);
            fwrite(teststr.toStdString().c_str(), teststr.length(), 1024*1024, fp);
        }
        fclose(fp);
        fp = nullptr;
    } else {
        return false;
    }

    connect(m_squashfsTask, &SquashfsTask::progressChanged, [=](const QJsonObject &processvalue) {
    //    qInfo() << "doMakeSquashfs : " << "process value is : " << processvalue;
    });
    connect(m_squashfsTask, &SquashfsTask::success, [=] {
        qInfo() << "doMakeSquashfs : " << "process value is : " << 100;
        m_eventLoop->quit();
    });
    connect(m_squashfsTask, &SquashfsTask::error, [=] {
        qInfo() << "doMakeSquashfs : " << "process value is : " << 100;
        m_eventLoop->quit();
        Q_EMIT error();
    });

//    // 保存设备信息
//    if (!writeGhostDeviceInfo(srcdir)) {
//        qInfo() << "writeGhostDeviceInfo failed !" << "path : " << srcdir;
//        return false;
//    }
    // 制作img文件
    return m_squashfsTask->makeSquashfs(srcdir, destfile);
}

TEST_F(MakeSquashfsTaskTest, all) {
    MakeSquashfsTaskTestHandle doMakeSquashfsTaskTestHandle(m_loop);

    QStringList args;
    args<<"-rf"<<TEST_DATA_DIR;
    EXPECT_TRUE(Process::spawnCmd("rm", args));

    QStringList mkdirArgs;
    mkdirArgs <<"-p"<<TEST_DATA_DIR"testsquashfs";
    EXPECT_TRUE(Process::spawnCmd("mkdir", mkdirArgs));

    if (doMakeSquashfsTaskTestHandle.doMakeSquashfs(TEST_DATA_DIR"testsquashfs", TEST_DATA_DIR"squashfsfiletest.squashfs")) {
        m_loop->exec();
    } else {
        m_loop->quit();
    }
}
