//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/IO/PythonExport.cpp
//! @brief     Implements Python export function in namespace IO.
//!
//! @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/IO/PythonExport.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/ToCore/SimulationToCore.h"
#include "GUI/View/Widget/AppConfig.h"
#include "GUI/View/Widget/FileDialog.h"
#include "Sim/Export/ExportToPython.h"
#include "Sim/Simulation/ScatteringSimulation.h"
#include <QFile>
#include <QMessageBox>
#include <QStandardPaths>
#include <QTextStream>

void IO::Py::saveScript(const SampleItem* sampleItem, const InstrumentItem* instrumentItem,
                        const SimulationOptionsItem* optionItem)
{
    // Create output first (so that we don't go through the file dialog for nothing)
    const auto simulation = GUI::ToCore::itemsToSimulation(sampleItem, instrumentItem, optionItem);
    const QString script = QString::fromStdString(::Py::Export::simulationPlotCode(*simulation));

    QString& dirname = gApp->script_export_dir;
    if (dirname.isEmpty())
        dirname = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);

    const QString filters("Python scripts (*.py)");

    QString fname = GUI::FileDialog::w1_1f("Save Python script", dirname, filters);
    if (fname.isEmpty())
        return;
    if (!fname.endsWith(".py"))
        fname += ".py";

    QFile file(fname);
    if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(nullptr, "Save Python file", "File could not be opened for writing!");
        return;
    }

    QTextStream out(&file);
    out << script;
    file.close();
}
