//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Sample/SampleModel.cpp
//! @brief     Implements class SampleModel
//!
//! @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/Sample/SampleModel.h"
#include "GUI/Model/Sample/ItemWithMaterial.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/Support/XML/UtilXML.h"
#include <QApplication>

namespace {
namespace Tag {

const QString Sample("Sample");
const QString SelectedIndex("SelectedIndex");

} // namespace Tag
} // namespace

SampleModel::~SampleModel() = default;

QVector<SampleItem*> SampleModel::sampleItems() const
{
    return QVector<SampleItem*>(m_samples.begin(), m_samples.end());
}

SampleItem* SampleModel::addSampleItem()
{
    addSampleItem(new SampleItem());
    return m_samples.back();
}

void SampleModel::addSampleItem(SampleItem* sample)
{
    m_samples.emplace_back(sample);
}

void SampleModel::removeSample(SampleItem* sample)
{
    m_samples.delete_element(sample);
}

QStringList SampleModel::sampleNames() const
{
    QStringList existingNames;
    for (const auto* item : m_samples)
        existingNames << item->sampleName();
    return existingNames;
}

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

    // samples
    for (const auto* sample : m_samples) {
        w->writeStartElement(Tag::Sample);
        sample->writeTo(w);
        w->writeEndElement();
    }

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

void SampleModel::readFrom(QXmlStreamReader* r)
{
    m_samples.clear();

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

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

        // sample
        if (tag == Tag::Sample) {
            addSampleItem()->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // selected index
        } else if (tag == Tag::SelectedIndex) {
            XML::readAttribute(r, XML::Attrib::value, &m_selectedIndex);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
