//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Toplevel/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/Toplevel/PythonScriptWidget.h"
#include "GUI/Application/ApplicationSettings.h"
#include "GUI/Model/ToCore/SimulationToCore.h"
#include "GUI/Support/Util/DesignerHelper.h"
#include "GUI/Support/Util/Style.h"
#include "GUI/View/Info/CautionSign.h"
#include "GUI/View/Info/PythonSyntaxHighlighter.h"
#include "GUI/View/Widget/StyledToolbar.h"
#include "Sim/Export/ExportToPython.h"
#include "Sim/Simulation/ScatteringSimulation.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QStandardPaths>
#include <QStyle>
#include <QTextEdit>
#include <QTextStream>
#include <QToolBar>
#include <QVBoxLayout>
#include <memory>

PythonScriptWidget::PythonScriptWidget(QWidget* parent)
    : QDialog(parent)
    , m_textEdit(new QTextEdit)
    , m_cautionSign(new CautionSign(m_textEdit))
{
    setObjectName("PythonScriptWidget");
    setWindowTitle("Python Script");
    setMinimumSize(128, 128);
    resize(512, 400);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    auto* toolbar = new StyledToolbar;
    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);

    m_textEdit->setReadOnly(true);
    QFont textFont("Monospace");
    m_textEdit->setFont(textFont);
    m_textEdit->setFontPointSize(DesignerHelper::getPythonEditorFontSize());
    m_textEdit->setLineWrapMode(QTextEdit::NoWrap);
    auto* highlighter = new PythonSyntaxHighlighter(m_textEdit->document());
    Q_UNUSED(highlighter);

    auto* mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    mainLayout->addWidget(toolbar);
    mainLayout->addWidget(m_textEdit);

    setLayout(mainLayout);

    setAttribute(Qt::WA_DeleteOnClose, true);
    GUI::Style::setResizable(this);
    appSettings->loadWindowSizeAndPos(this);
}


PythonScriptWidget::~PythonScriptWidget()
{
    appSettings->saveWindowSizeAndPos(this);
}

void PythonScriptWidget::generatePythonScript(const SampleItem& sampleItem,
                                              const InstrumentItem& instrumentItem,
                                              const SimulationOptionsItem& optionItem,
                                              const QString& outputDir)
{
    m_outputDir = outputDir;
    m_cautionSign->clear();

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

        QString code = QString::fromStdString(Py::Export::simulationPlotCode(*simulation));
        m_textEdit->clear();
        m_textEdit->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_cautionSign->setCautionMessage(message);
    }
}

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

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

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

    if (fileName.isEmpty())
        return;

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

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