//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Sample/ScriptPanel.cpp
//! @brief     Implements class ScriptPanel.
//!
//! @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/Sample/ScriptPanel.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/Model/ToCore/SampleToCore.h"
#include "GUI/Model/Type/UpdateTimer.h"
#include "GUI/View/Base/Fontsize.h"
#include "GUI/View/Info/CautionSign.h"
#include "GUI/View/Info/PythonSyntaxHighlighter.h"
#include "Sample/Multilayer/MultiLayer.h"
#include "Sim/Export/ExportToPython.h"
#include <QScrollBar>
#include <QStackedWidget>
#include <QVBoxLayout>

namespace {

const int accumulateUpdatesDuringMsec = 20.;

} // namespace

ScriptPanel::ScriptPanel(QWidget* parent)
    : QWidget(parent)
    , m_text_edit(new QTextEdit)
    , m_highlighter(nullptr)
    , m_update_timer(new UpdateTimer(accumulateUpdatesDuringMsec, this))
    , m_caution_sign(new CautionSign(m_text_edit))
    , m_current_sample(nullptr)
{
    setWindowTitle("Python Script");
    setObjectName("ScriptPanel");

    m_text_edit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    auto* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addWidget(m_text_edit);

    m_text_edit->setReadOnly(true);
    QFont textFont("Monospace");
    m_text_edit->setFont(textFont);
    m_text_edit->setFontPointSize(GUI::Style::fontSizeRegular());

    connect(m_update_timer, &UpdateTimer::timeToUpdate, this, &ScriptPanel::updateEditor);
}

void ScriptPanel::setCurrentSample(SampleItem* sampleItem)
{
    m_current_sample = sampleItem;
    updateEditor();
}

void ScriptPanel::onSampleModified()
{
    if (isVisible())
        m_update_timer->scheduleUpdate();
}

void ScriptPanel::updateEditor()
{
    if (!m_highlighter) {
        m_highlighter = new PythonSyntaxHighlighter(m_text_edit->document());
        m_text_edit->setLineWrapMode(QTextEdit::NoWrap);
    }

    const int oldScrollbarValue = m_text_edit->verticalScrollBar()->value();

    const QString codeSnippet = generateCodeSnippet();
    if (!codeSnippet.isEmpty())
        m_text_edit->setText(codeSnippet);
    else
        m_text_edit->clear();

    m_text_edit->verticalScrollBar()->setValue(oldScrollbarValue);
}

void ScriptPanel::showEvent(QShowEvent*)
{
    m_update_timer->scheduleUpdate();
}

void ScriptPanel::hideEvent(QHideEvent*)
{
    m_update_timer->reset();
}

QString ScriptPanel::generateCodeSnippet()
{
    m_caution_sign->clear();

    if (m_current_sample == nullptr)
        return {};

    QString result;
    try {
        auto sample = GUI::ToCore::itemToSample(*m_current_sample);
        result.append(QString::fromStdString(Py::Export::sampleCode(*sample)));
    } catch (const std::exception& ex) {
        QString message =
            QString("Generation of Python Script failed. Code is not complete.\n\n"
                    "It can happen if sample requires further assembling or some of sample "
                    "parameters are not valid. See details below.\n\n%1")
                .arg(QString::fromStdString(ex.what()));

        m_caution_sign->setCautionMessage(message);
    }

    return result;
}
