//  ************************************************************************************************
//
//  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;
    }
    onJobStatusChanged(m_job_item->batchInfo()->status());
    onJobCommentsChanged(m_job_item->batchInfo()->comments());

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

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

    QSignalBlocker b(m_job_item->batchInfo());
    m_job_item->batchInfo()->setComments(m_comments_editor->toPlainText());
}

void JobMessagesDisplay::onJobCommentsChanged(const QString& comments)
{
    QSignalBlocker b(m_comments_editor);
    m_comments_editor->setPlainText(comments);
}

void JobMessagesDisplay::onJobStatusChanged(JobStatus status)
{
    if (isRunning(status))
        return;

    QSignalBlocker b(m_comments_editor);

    m_comments_editor->setTextColor(isFailed(status) ? Qt::red : Qt::black);
    m_comments_editor->setPlainText(m_comments_editor->toPlainText());
}

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