//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/FitControl/FitWorkerLauncher.cpp
//! @brief     Implements class FitWorkerLauncher.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/FitControl/FitWorkerLauncher.h"
#include "GUI/View/FitControl/FitWorker.h"
#include <QThread>

FitWorkerLauncher::FitWorkerLauncher(QObject* parent)
    : QObject(parent)
    , m_is_fit_running(false)
{
}

void FitWorkerLauncher::runFitting(std::shared_ptr<FitObjectiveBuilder> suite)
{
    if (!suite || m_is_fit_running)
        return;

    auto* thread = new QThread();
    auto* fw = new FitWorker(suite);
    fw->moveToThread(thread);

    // start fitting when thread starts
    connect(thread, &QThread::started, fw, &FitWorker::startFit);
    connect(fw, &FitWorker::started, this, &FitWorkerLauncher::intern_workerStarted);

    connect(this, &FitWorkerLauncher::intern_interruptFittingWorker, fw,
            &FitWorker::interruptFitting, Qt::DirectConnection);

    connect(fw, &FitWorker::error, this, &FitWorkerLauncher::intern_error);
    connect(fw, &FitWorker::finished, this, &FitWorkerLauncher::intern_workerFinished);

    // delete fitting worker and thread when done
    connect(fw, &FitWorker::finished, fw, &FitWorker::deleteLater);
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);

    m_is_fit_running = true;
    thread->start();
}

const QDateTime& FitWorkerLauncher::fitStart() const
{
    return m_fit_start;
}

const QDateTime& FitWorkerLauncher::fitEnd() const
{
    return m_fit_end;
}

void FitWorkerLauncher::interruptFitting()
{
    if (m_is_fit_running)
        emit intern_interruptFittingWorker(QPrivateSignal());
}

void FitWorkerLauncher::intern_workerFinished()
{
    m_is_fit_running = false;
    m_fit_end = QDateTime::currentDateTime();
    emit fittingFinished();
}

void FitWorkerLauncher::intern_workerStarted()
{
    m_fit_start = QDateTime::currentDateTime();
    m_fit_end = QDateTime();
    emit fittingStarted();
}

void FitWorkerLauncher::intern_error(const QString& mesg)
{
    emit fittingError(mesg);
}
