//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Loader/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/Loader/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 <QMessageBox>

namespace {

template <class T> void saveToXML(const QString& fname, const T* t);
template <class 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 = &RW::saveComponentToXML<class InstrumentItem>;
auto dummy_loadXML_InstrumentItem = &RW::loadComponentFromXML<class InstrumentItem>;


template <class T> void RW::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 <class T> T* RW::loadComponentFromXML(const QString& type)
{
    QString fname = GUI::FileDialog::r1_1f("Load " + type, gApp->xml_dir, "XML files (*.xml)");
    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;
}
