#include "easyncworker.h"

#include <QEventLoop>
#include <QTimer>

using namespace uos_ai;

static int TimeOutMs = 2000;

EAsyncWorker::EAsyncWorker(QObject *parent)
{

}

bool EAsyncWorker::executeSynchronouslyGeneric(AsyncWorkerType type)
{
    emit sigAsyncWorker(type);

    QEventLoop loop;
    QTimer timer;
    bool success = false;

    QMetaObject::Connection conn = QObject::connect(this, &EAsyncWorker::sigWorkerFinished, this, [&loop, &success, type](int finishedType){
        if (type == finishedType) {
            success = true;
            qInfo() << type << "async task succuss!";
            loop.quit();
        }
    });
    QObject::connect(&timer, &QTimer::timeout, [&loop, conn]() {
        loop.quit();
    });
    timer.start(TimeOutMs);

    loop.exec(QEventLoop::ProcessEventsFlag::EventLoopExec);
    disconnect(conn);

    if (!success) {
        qInfo() << "异步操作超时或失败";
        return false;
    }

    return true;
}

bool EAsyncWorker::chatInitSyncWorker()
{
    QEventLoop loop;
    QTimer timer;
    bool success = false;

    QMetaObject::Connection conn = QObject::connect(this, &EAsyncWorker::sigChatInitSyncWorkerFinished, this, [&loop, &success](){
        success = true;
        qInfo() << "chat init async task succuss!";
        loop.quit();
    });
    QObject::connect(&timer, &QTimer::timeout, [&loop]() {
        loop.quit();
    });
    timer.start(TimeOutMs);

    loop.exec(QEventLoop::ProcessEventsFlag::EventLoopExec);
    disconnect(conn);

    if (!success) {
        qInfo() << "异步操作超时或失败";
        return false;
    }

    return true;
}
