// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2014-2020, The Monero Project.

#include "scheduler.h"

FutureScheduler::FutureScheduler(QObject *parent)
    : QObject(parent), Alive(0), Stopping(false)
{
    qDebug() << Q_FUNC_INFO;
}

FutureScheduler::~FutureScheduler()
{
    qDebug() << Q_FUNC_INFO;
    shutdownWaitForFinished();
}

void FutureScheduler::shutdownWaitForFinished() noexcept
{
    qDebug() << Q_FUNC_INFO << "begin";
    QMutexLocker locker(&Mutex);

    Stopping = true;
    while (Alive > 0)
    {
        Condition.wait(&Mutex);
    }
    qDebug() << Q_FUNC_INFO << "end";
}

QPair<bool, QFuture<void>> FutureScheduler::run(std::function<void()> function) noexcept
{
    qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
    return execute<void>([this, function](QFutureWatcher<void> *) {
        return QtConcurrent::run([this, function] {
            try
            {
                qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
                function();
            }
            catch (const std::exception &exception)
            {
                qWarning() << "Exception thrown from async function: " << exception.what();
            }
            done();
        });
    });
}

//QPair<bool, QFuture<QJSValueList>> FutureScheduler::run(std::function<QJSValueList()> function, const QJSValue &callback)
//{
//    if (!callback.isCallable())
//    {
//        throw std::runtime_error("js callback must be callable");
//    }

//    return execute<QJSValueList>([this, function, callback](QFutureWatcher<QJSValueList> *watcher) {
//        connect(watcher, &QFutureWatcher<QJSValueList>::finished, [watcher, callback] {
//            QJSValue(callback).call(watcher->future().result());
//        });
//        return QtConcurrent::run([this, function] {
//            QJSValueList result;
//            try
//            {
//                result = function();
//            }
//            catch (const std::exception &exception)
//            {
//                qWarning() << "Exception thrown from async function: " << exception.what();
//            }
//            done();
//            return result;
//        });
//    });
//}

bool FutureScheduler::add() noexcept
{
    qDebug() << Q_FUNC_INFO << "begin";
    QMutexLocker locker(&Mutex);

    if (Stopping)
    {
        qDebug() << Q_FUNC_INFO << "end";
        return false;
    }

    ++Alive;
    qDebug() << Q_FUNC_INFO << "end";
    return true;
}

void FutureScheduler::done() noexcept
{
    qDebug() << Q_FUNC_INFO << "begin";
    {
        QMutexLocker locker(&Mutex);
        --Alive;
    }

    Condition.wakeAll();

    qDebug() << Q_FUNC_INFO << "end";
}
