//  ************************************************************************************************
//
//  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) {
        m_comments_editor->clear();
        return;
    }
    const bool ok = isFailed(m_job_item->batchInfo()->status());
    m_comments_editor->setTextColor(ok ? Qt::black : Qt::red);

    connect(m_job_item, &QObject::destroyed, this, &JobMessagesDisplay::onJobDestroyed,
            Qt::UniqueConnection);
    connect(m_job_item->batchInfo(), &BatchInfo::jobCommentsChanged, this,
            &JobMessagesDisplay::onJobCommentsChanged, Qt::UniqueConnection);
}

void JobMessagesDisplay::onCommentsEdited()
{
    if (!m_job_item)
        return;

    m_job_item->batchInfo()->blockSignals(true);
    m_job_item->batchInfo()->setComments(m_comments_editor->toPlainText());
    m_job_item->batchInfo()->blockSignals(false);
}

void JobMessagesDisplay::onJobCommentsChanged(const QString& comments)
{
    ASSERT(m_job_item)

    m_comments_editor->blockSignals(true);
    m_comments_editor->setPlainText(comments);
    m_comments_editor->blockSignals(false);
}

void JobMessagesDisplay::onJobDestroyed()
{
    m_job_item = nullptr;
}
