//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Job/JobsSet.cpp
//! @brief     Implements class JobsSet.
//!
//! @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/Model/Job/JobsSet.h"
#include "GUI/Model/File/DatafileItem.h"
#include "GUI/Model/Job/BatchInfo.h"
#include "GUI/Model/Job/JobStatus.h"
#include "GUI/Model/Par/ParameterTreeItems.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString Job("Job");
const QString CurrentIndex("CurrentIndex");

} // namespace Tag
} // namespace


JobsSet::JobsSet(QObject* parent)
    : QObject(parent)
{
    setObjectName("JobsSet");
}

JobsSet::~JobsSet() = default;

void JobsSet::writeTo(QXmlStreamWriter* w) const
{
    for (const auto* job : *this) {
        w->writeStartElement(Tag::Job);
        XML::writeAttribute(w, XML::Attrib::name, job->batchInfo()->jobName());
        job->writeTo(w);
        w->writeEndElement();
    }
    XML::writeTaggedValue(w, Tag::CurrentIndex, (int)currentIndex());
}

void JobsSet::readFrom(QXmlStreamReader* r)
{
    ASSERT(empty());

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Job) {
            auto* job_item = createJobItem();
            XML::readTaggedElement(r, tag, *job_item);
            emit jobAdded(job_item);
        } else if (tag == Tag::CurrentIndex) {
            size_t i = XML::readTaggedInt(r, tag);
            setCurrentIndex(i);
        } else
            r->skipCurrentElement();
    }

    if (r->hasError())
        throw std::runtime_error(r->errorString().toStdString());
}

void JobsSet::saveAllDatafields(const QString& projectDir) const
{
    for (const JobItem* job : *this)
        job->saveDatafields(projectDir);

    dataFilesCleaner.cleanOldFiles(projectDir, dataItems());
}

void JobsSet::loadAllDatafields(const QString& projectDir)
{
    for (JobItem* job : *this)
        job->loadDatafields(projectDir);

    dataFilesCleaner.recollectDataNames(dataItems());
}

JobItem* JobsSet::createJobItem()
{
    auto* job_item = new JobItem;
    push_back(job_item);
    return job_item;
}

//! Main method to add a job
void JobsSet::addJobItem(JobItem* job_item)
{
    job_item->batchInfo()->setJobName(generateJobName());
    push_back(job_item);
    emit jobAdded(job_item);
}

//! restore instrument and sample model from backup for given JobItem
void JobsSet::restoreBackupPars(JobItem* job_item, int index)
{
    job_item->parameterContainerItem()->restoreBackupValues(index);
}

QVector<DataItem*> JobsSet::dataItems() const
{
    QVector<DataItem*> result;

    for (auto* job_item : *this) {
        if (auto* dataItem = job_item->simulatedDataItem())
            result.push_back(dataItem);

        if (const auto* real_data = dynamic_cast<const DatafileItem*>(job_item->dfileItem()))
            if (auto* data_item = real_data->dataItem())
                result.push_back(data_item);
    }
    return result;
}

void JobsSet::cancelJob(JobItem* job_item)
{
    job_item->haltWorker();
}

void JobsSet::removeJob(JobItem* job_item)
{
    ASSERT(job_item);
    job_item->haltWorker();
    delete_element(job_item);
    emit jobPlotContextChanged();
}

bool JobsSet::hasUnfinishedJobs() const
{
    for (const JobItem* job_item : *this)
        if (isFitting(job_item->batchInfo()->status()))
            return true;
    return false;
}

//! Submits job and run it in a thread.

void JobsSet::runJob(JobItem* job_item)
{
    if (job_item->thread())
        return;

    connect(job_item, &JobItem::progressIncremented, this, &JobsSet::onProgressUpdate,
            Qt::UniqueConnection);
    connect(job_item, &JobItem::jobFinished, this, &JobsSet::onFinishedJob, Qt::UniqueConnection);

    job_item->initWorker();
    job_item->thread()->start();
}

//  ------------------------------------------------------------------------------------------------
//  private slots
//  ------------------------------------------------------------------------------------------------

//! Performs necessary actions when job is finished.
void JobsSet::onFinishedJob(JobItem* job_item)
{
    onProgressUpdate();
    emit newJobFinished(job_item);
    emit jobPlotContextChanged();
}

//! Estimates global progress from the progress of multiple running jobs and emits signal.
void JobsSet::onProgressUpdate()
{
    int global_progress = 0;
    int nRunningJobs = 0;
    for (const JobItem* job_item : *this)
        if (isRunning(job_item->batchInfo()->status())) {
            global_progress += job_item->batchInfo()->progress();
            nRunningJobs++;
        }

    emit globalProgress(nRunningJobs ? global_progress / nRunningJobs : -1);
}

//! Cancels all running jobs.
void JobsSet::onCancelAllJobs()
{
    for (auto* job_item : *this)
        job_item->haltWorker();
}

//  ------------------------------------------------------------------------------------------------
//  private fcts
//  ------------------------------------------------------------------------------------------------

//! generates numbered job name with new/unused number
QString JobsSet::generateJobName() const
{
    int maxJobIndex = 0;
    for (const JobItem* job_item : *this)
        if (job_item->batchInfo()->jobName().startsWith("job"))
            maxJobIndex = std::max(maxJobIndex, job_item->batchInfo()->jobName().mid(3).toInt());
    return QString("job%1").arg(maxJobIndex + 1);
}
