//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Fit/JobRealTimeWidget.cpp
//! @brief     Implements class JobRealTimeWidget
//!
//! @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/Fit/JobRealTimeWidget.h"
#include "GUI/Model/Model/JobModel.h"
#include "GUI/View/Fit/ParameterTuningWidget.h"
#include "GUI/View/Tool/mainwindow_constants.h"
#include <QSettings>
#include <QVBoxLayout>

namespace {

const bool reuse_widget = true;
}

JobRealTimeWidget::JobRealTimeWidget(JobModel* jobModel, QWidget* parent)
    : QWidget(parent)
    , m_stackedWidget(new ItemStackPresenter<ParameterTuningWidget>(reuse_widget))
    , m_jobModel(jobModel)
{
    setWindowTitle(GUI::Constants::JobRealTimeWidgetName);
    setObjectName("JobRealTimeWidget");
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    auto* mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    mainLayout->addWidget(m_stackedWidget);
    setLayout(mainLayout);

    setFixedWidth(GUI::Constants::FIT_ACTIVITY_PANEL_WIDTH);
    applySettings();
}

void JobRealTimeWidget::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    emit widthChanged(width());
    setMinimumWidth(0);
    setMaximumWidth(QWIDGETSIZE_MAX);
}

ParameterTuningWidget* JobRealTimeWidget::parameterTuningWidget(JobItem* jobItem)
{
    return m_stackedWidget->itemWidget(jobItem);
}

void JobRealTimeWidget::setJobItem(JobItem* jobItem)
{
    if (!isValidJobItem(jobItem)) {
        m_stackedWidget->hideWidgets();
        return;
    }
    m_stackedWidget->setItem(jobItem, m_jobModel);
}

//! Returns true if JobItem is valid for real time simulation.

bool JobRealTimeWidget::isValidJobItem(JobItem* item)
{
    return item && (item->isCompleted() || item->isCanceled() || item->isFailed());
}

void JobRealTimeWidget::applySettings()
{
    QSettings settings;
    if (settings.childGroups().contains(GUI::Constants::S_FIT_ACTIVITY_PANEL)) {
        settings.beginGroup(GUI::Constants::S_FIT_ACTIVITY_PANEL);
        setFixedWidth(settings.value(GUI::Constants::S_FIT_ACTIVITY_PANEL_SIZE).toSize().width());
        settings.endGroup();
    }
}
