//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Sim/InstrumentsSet.cpp
//! @brief     Implement class InstrumentsSet
//!
//! @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/InstrumentsSet.h"
#include "GUI/Model/Sim/InstrumentsCatalog.h"

namespace {
namespace Tag {

const QString Instrument("Instrument");
const QString CurrentIndex("CurrentIndex");

} // namespace Tag
} // namespace

InstrumentsSet::InstrumentsSet() = default;
InstrumentsSet::~InstrumentsSet() = default;

void InstrumentsSet::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // instruments
    for (const auto* t : *this) {
        w->writeStartElement(Tag::Instrument);
        t->writeTo(w);
        w->writeEndElement();
    }

    // selected index
    w->writeStartElement(Tag::CurrentIndex);
    XML::writeAttribute(w, XML::Attrib::value, currentIndex());
    w->writeEndElement();
}

void InstrumentsSet::readFrom(QXmlStreamReader* r)
{
    clear();

    const uint version = XML::readUInt(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // instrument
        if (tag == Tag::Instrument) {
            add_item(PolyItem<InstrumentsCatalog>().readItemFrom(r));
            XML::gotoEndElementOfTag(r, tag);

            // selected index
        } else if (tag == Tag::CurrentIndex) {
            setCurrentIndex(XML::readSize(r, XML::Attrib::value));
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

InstrumentItem* InstrumentsSet::findInstrumentItemById(const QString& instrumentId) const
{
    for (auto* t : *this)
        if (t->id() == instrumentId)
            return t;
    return nullptr;
}

bool InstrumentsSet::instrumentExists(const QString& instrumentId) const
{
    return findInstrumentItemById(instrumentId) != nullptr;
}
