//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/IO/ComponentRW.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/IO/ComponentRW.h"
#include "GUI/Model/Sim/InstrumentItems.h"
#include "GUI/Model/Sim/InstrumentXML.h"
#include "GUI/View/Widget/AppConfig.h"
#include "GUI/View/Widget/FileDialog.h"
#include <QFileDialog>
#include <QMessageBox>

namespace {

template <typename T> void saveToXML(const QString& fname, const T* t);
template <typename T> T* loadFromXML(const QString& fname);

template <> void saveToXML<InstrumentItem>(const QString& fname, const InstrumentItem* t)
{
    InstrumentXML::save(fname, t);
}
template <> InstrumentItem* loadFromXML<InstrumentItem>(const QString& fname)
{
    return InstrumentXML::load(fname);
}

} // namespace

// Force instantiation by assigning the function to a global variable that will never be used:
auto dummy_saveXML_InstrumentItem = &IO::saveComponentToXML<class InstrumentItem>;
auto dummy_loadXML_InstrumentItem = &IO::loadComponentFromXML<class InstrumentItem>;


template <typename T> void IO::saveComponentToXML(const QString& type, const T* t)
{
    if (!t)
        return;

    QString fname = GUI::FileDialog::w1_1f("Save " + type, gApp->xml_dir, "XML files (*.xml)",
                                           t->name() + ".xml");
    if (fname.isEmpty())
        return;

    try {
        ::saveToXML<T>(fname, t);
    } catch (const std::exception& ex) {
        QMessageBox(QMessageBox::Warning, "BornAgain: failed saving", ex.what(), QMessageBox::Ok,
                    nullptr)
            .exec();
    }
}

template <typename T> T* IO::loadComponentFromXML(const QString& type)
{
    QString fname = QFileDialog::getOpenFileName(gApp->mainWindow, "Load " + type, gApp->xml_dir,
                                                 "XML files (*.xml)", nullptr);
    if (fname.isEmpty())
        return nullptr;

    try {
        return ::loadFromXML<T>(fname);
    } catch (const std::exception& ex) {
        QMessageBox(QMessageBox::Warning, "BornAgain: failed loading", ex.what(), QMessageBox::Ok,
                    nullptr)
            .exec();
    }
    return nullptr;
}
