//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Loader/PythonScriptWidget.cpp
//! @brief     Implements class PythonScriptWidget.
//!
//! @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/Loader/PythonScriptWidget.h"
#include "GUI/Model/ToCore/SimulationToCore.h"
#include "GUI/View/Base/Fontsize.h"
#include "GUI/View/Info/CautionSign.h"
#include "GUI/View/Info/PythonSyntaxHighlighter.h"
#include "GUI/View/Widget/AppConfig.h"
#include "GUI/View/Widget/StyledToolbar.h"
#include "GUI/View/Widget/WidgetSettings.h"
#include "Sim/Export/ExportToPython.h"
#include "Sim/Simulation/ScatteringSimulation.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QStandardPaths>
#include <QStyle>
#include <QTextStream>
#include <QToolBar>
#include <QVBoxLayout>
#include <memory>

PythonScriptWidget::PythonScriptWidget(QWidget* parent)
    : QDialog(parent)
    , m_text_edit(new QTextEdit)
    , m_caution_sign(new CautionSign(m_text_edit))
{
    auto* layout = new QVBoxLayout;
    setLayout(layout);
    layout->setContentsMargins(0, 0, 0, 0);

    setObjectName("PythonScriptWidget");
    setWindowTitle("Python Script");
    setMinimumSize(128, 128);
    resize(512, 400);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    auto* toolbar = new StyledToolbar;
    layout->addWidget(toolbar);
    toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);

    auto* exportAction = new QAction(this);
    exportAction->setIcon(QIcon(":/images/content-save-outline.svg"));
    exportAction->setText("Save to file");
    exportAction->setToolTip("Opens dialog to save given script into the file");
    connect(exportAction, &QAction::triggered, this, &PythonScriptWidget::onExportToFileButton);

    toolbar->addAction(exportAction);

    layout->addWidget(m_text_edit);
    m_text_edit->setReadOnly(true);
    QFont textFont("Monospace");
    m_text_edit->setFont(textFont);
    m_text_edit->setFontPointSize(GUI::Style::fontSizeRegular());
    m_text_edit->setLineWrapMode(QTextEdit::NoWrap);
    auto* highlighter = new PythonSyntaxHighlighter(m_text_edit->document());
    Q_UNUSED(highlighter);

    setAttribute(Qt::WA_DeleteOnClose, true);
    GUI::Style::setResizable(this);
    GUI::WidgetSettings::load(this);
}

PythonScriptWidget::~PythonScriptWidget()
{
    GUI::WidgetSettings::save(this);
}

void PythonScriptWidget::generatePythonScript(const SampleItem* sampleItem,
                                              const InstrumentItem* instrumentItem,
                                              const SimulationOptionsItem& optionItem,
                                              const QString& outputDir)
{
    if (!sampleItem || !instrumentItem)
        return;
    m_output_dir = outputDir;
    m_caution_sign->clear();

    try {
        const auto simulation =
            GUI::ToCore::itemsToSimulation(*sampleItem, *instrumentItem, optionItem);

        QString code = QString::fromStdString(Py::Export::simulationPlotCode(*simulation));
        m_text_edit->clear();
        m_text_edit->setText(code);
    } 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);
    }
}

void PythonScriptWidget::onExportToFileButton()
{
    QString dirname(m_output_dir);
    if (dirname.isEmpty())
        dirname = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);

    QString filters("Python scripts (*.py)");
    QString defaultFilter("Python scripts (*.py)");
    QString defaultName = dirname + "/untitled";

    QString fname = QFileDialog::getSaveFileName(
        nullptr, "Save file", defaultName, filters, &defaultFilter,
        gApp->useNativeFileDialog() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog);

    if (fname.isEmpty())
        return;

    if (!fname.endsWith(".py"))
        fname += ".py";

    QFile file(fname);
    if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(this, "Save Python file", "File could not be opened for writing!");
        return;
    }
    QTextStream out(&file);
    out << m_text_edit->toPlainText();
    file.close();
    raise();
}
