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

JobMessagesDisplay::JobMessagesDisplay(QWidget* parent, Qt::WindowFlags f)
    : QWidget(parent, f)
    , m_comments_editor(new QTextEdit(this))
    , m_job_item(nullptr)
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
    setWindowTitle("Job Properties");

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

    layout->addWidget(new QLabel("Messages"));
    layout->addWidget(m_comments_editor);

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

    setMinimumWidth(10);
    setMinimumHeight(190);
}

void JobMessagesDisplay::setJobItem(JobItem* jobItem)
{
    m_job_item = jobItem;
    if (m_job_item) {
        ASSERT(m_job_item->batchInfo());
        const bool ok = isFailed(m_job_item->batchInfo()->status());
        m_comments_editor->setTextColor(ok ? Qt::black : Qt::red);
        connect(m_job_item->batchInfo(), &BatchInfo::jobCommentsChanged, [this](const QString&) {
            if (!m_job_item)
                return;
            ASSERT(m_job_item->batchInfo());
            if (m_job_item->batchInfo()->comments() == m_comments_editor->toPlainText())
                return;
            m_comments_editor->blockSignals(true);
            m_comments_editor->setPlainText(m_job_item->batchInfo()->comments());
            m_comments_editor->blockSignals(false);
        });
    } else
        m_comments_editor->clear();
}

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