//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Job/JobEditor.cpp
//! @brief     Implements class JobEditor.
//!
//! @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/Job/JobEditor.h"
#include "GUI/Model/Job/BatchInfo.h"
#include "GUI/Model/Job/JobItem.h"
#include "GUI/Model/Job/JobStatus.h"
#include "GUI/View/Base/mainwindow_constants.h"
#include "GUI/View/Job/JobparQModel.h"
#include <QHeaderView>
#include <QSettings>
#include <QVBoxLayout>

namespace {

enum ETabId { JOB_PROPERTIES, JOB_MESSAGES };
} // namespace

//--------------------------------------------------------------------------------------------------
// public member functions
//--------------------------------------------------------------------------------------------------

JobEditor::JobEditor(QWidget* parent, Qt::WindowFlags f)
    : QWidget(parent, f)
    , m_tab_widget(new QTabWidget(this))
    , m_properties_view(new QTreeView(this))
    , m_properties_model(new JobparQModel(this))
    , m_comments_editor(new QTextEdit(this))
    , m_job_item(nullptr)
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
    setWindowTitle(GUI::Style::JobEditorName);

    auto* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    m_tab_widget->setTabPosition(QTabWidget::South);
    layout->addWidget(m_tab_widget);

    m_properties_view->setRootIsDecorated(false);
    m_properties_view->setAlternatingRowColors(true);
    m_tab_widget->insertTab(JOB_PROPERTIES, m_properties_view, "Job Properties");

    m_properties_view->setModel(m_properties_model);
    m_properties_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

    m_tab_widget->insertTab(JOB_MESSAGES, m_comments_editor, "Messages");

    connect(m_comments_editor, &QTextEdit::textChanged, this, &JobEditor::onCommentsEdited);

    setMinimumWidth(10);
    setMinimumHeight(190);
    applySettings();
}

JobEditor::~JobEditor()
{
    if (m_job_item)
        disconnect(m_job_item, nullptr, this, nullptr);
    saveSettings();
}

void JobEditor::setJobItem(JobItem* jobItem)
{
    if (m_job_item)
        disconnect(m_job_item, nullptr, this, nullptr);
    m_job_item = jobItem;
    m_properties_model->setJobItem(m_job_item);
    if (m_job_item) {
        if (isFailed(m_job_item->batchInfo()->status()))
            m_tab_widget->tabBar()->setTabTextColor(JOB_MESSAGES, Qt::red);
        else
            m_tab_widget->tabBar()->setTabTextColor(JOB_MESSAGES, Qt::black);

        if (m_job_item->batchInfo()->comments().isEmpty())
            m_tab_widget->setCurrentIndex(JOB_PROPERTIES);
        else
            m_tab_widget->setCurrentIndex(JOB_MESSAGES);
        m_comments_editor->setText(m_job_item->batchInfo()->comments());

        notifyJobPropertyChange();
    } else
        m_comments_editor->clear();
}

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

void JobEditor::onCommentsEdited()
{
    if (m_job_item) {
        m_job_item->blockSignals(true);
        m_job_item->batchInfo()->setComments(m_comments_editor->toPlainText());
        m_job_item->blockSignals(false);
    }
}

//--------------------------------------------------------------------------------------------------
// private member functions
//--------------------------------------------------------------------------------------------------

void JobEditor::notifyJobPropertyChange()
{
    connect(m_job_item->batchInfo(), &BatchInfo::jobCommentsChanged, [this](const QString&) {
        if (m_job_item && m_job_item->batchInfo()->comments() != m_comments_editor->toPlainText()) {
            m_comments_editor->blockSignals(true);
            m_comments_editor->setPlainText(m_job_item->batchInfo()->comments());
            m_comments_editor->blockSignals(false);
        }
    });
}

void JobEditor::applySettings()
{
    QSettings settings;
    if (settings.childGroups().contains(GUI::Style::S_JOB_PROPERTIES_WIDGET)) {
        settings.beginGroup(GUI::Style::S_JOB_PROPERTIES_WIDGET);
        m_tab_widget->setCurrentIndex(
            settings.value(GUI::Style::S_JOB_PROPERTIES_WIDGET_CURRENT_TAB).toInt());
        settings.endGroup();
    }
}

void JobEditor::saveSettings()
{
    QSettings settings;
    settings.beginGroup(GUI::Style::S_JOB_PROPERTIES_WIDGET);
    settings.setValue(GUI::Style::S_JOB_PROPERTIES_WIDGET_CURRENT_TAB,
                      m_tab_widget->currentIndex());
    settings.endGroup();
    settings.sync();
}
