//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Sim/InstrumentXML.cpp
//! @brief     Implements class InstrumentXML.
//!
//! @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/Model/Sim/InstrumentXML.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Descriptor/PolyItem.h"
#include "GUI/Model/Sim/InstrumentItems.h"
#include "GUI/Model/Sim/InstrumentsCatalog.h"
#include "GUI/Model/Util/UtilXML.h"
#include <QFile>

namespace {

const QString XML_ROOT_TAG = "BornAgain_Instrument";
const QString XML_VERSION_TAG = "version";

} // namespace

void InstrumentXML::save(const QString& fname, const InstrumentItem* t)
{
    QFile file(fname);

    if (!file.open(QFile::ReadWrite | QIODevice::Truncate | QFile::Text))
        throw std::runtime_error("Cannot open instrument file for writing");

    QXmlStreamWriter w(&file);
    w.setAutoFormatting(true);
    w.writeStartDocument();
    w.writeStartElement(XML_ROOT_TAG);

    const uint typeIndex = static_cast<uint>(InstrumentsCatalog::type(t));
    XML::writeAttribute(&w, XML::Attrib::type, typeIndex);
    // The next line allows to see the name of item type in XML. May be skipped while reading.
    XML::writeAttribute(&w, XML::Attrib::name,
                        InstrumentsCatalog::uiInfo(InstrumentsCatalog::type(t)).menuEntry);

    t->writeTo(&w);
    w.writeEndElement();
    w.writeEndDocument();

    file.close();
}

InstrumentItem* InstrumentXML::load(const QString& fname)
{
    InstrumentItem* t = nullptr;

    QFile file(fname);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        throw std::runtime_error("Cannot open instrument file for reading");
    QXmlStreamReader r(&file);
    if (r.atEnd())
        throw std::runtime_error("Empty instrument file?");
    r.readNext();
    if (!r.isStartDocument())
        throw std::runtime_error("Missing StartDocument in instrument file");
    r.readNext();
    if (!r.isStartElement())
        throw std::runtime_error("Missing start element in instrument file");
    if (r.name() != XML_ROOT_TAG)
        throw std::runtime_error("Missing root tag in instrument file, found "
                                 + r.name().toString().toStdString());
    const int found_version = r.attributes().value(XML_VERSION_TAG).toString().toInt();
    if (found_version != 1)
        throw std::runtime_error("Unsupported version of instrument element");
    const uint typeIndex = XML::readUIntAttribute(&r, XML::Attrib::type);
    const auto type = static_cast<typename InstrumentsCatalog::Type>(typeIndex);
    t = InstrumentsCatalog::create(type);
    ASSERT(t);
    t->readFrom(&r);

    if (r.hasError())
        throw std::runtime_error(QString("Error in instrument file, line %1, column %2: %3")
                                     .arg(r.lineNumber())
                                     .arg(r.columnNumber())
                                     .arg(r.errorString())
                                     .toStdString());
    file.close();

    return t;
}
