//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Device/InstrumentModel.h
//! @brief     Defines class InstrumentModel
//!
//! @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)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_GUI_MODEL_DEVICE_INSTRUMENTMODEL_H
#define BORNAGAIN_GUI_MODEL_DEVICE_INSTRUMENTMODEL_H

#include "GUI/Model/Descriptor/SelectionProperty.h"
#include "GUI/Model/Device/InstrumentItemCatalog.h"
#include <QStringList>
#include <QVector>
#include <QXmlStreamWriter>
#include <functional>
#include <memory>

class InstrumentItem;

class InstrumentModel {
public:
    ~InstrumentModel();

    template <typename T>
    T* addInstrumentItem()
    {
        auto* t = new T();
        emplace_back(t);
        return t;
    }

    void removeInstrument(InstrumentItem* instrument);
    void clear();

    void writeTo(QXmlStreamWriter* w) const;
    void readFrom(QXmlStreamReader* r);

    void emplace_back(InstrumentItem* item); // TODO Qt6 emplace

    //! Inserts a deep copy (also of any non XML data in a pointwise axis)
    //! The id will not be copied, but a new unique one will be created
    //! Returns the newly created instrument.
    InstrumentItem* insertItemCopy(const InstrumentItem& source);

    QVector<InstrumentItem*> instrumentItems() const;
    QVector<InstrumentItem*> instrument2DItems() const;
    QVector<InstrumentItem*>
    instrumentItems(const std::function<bool(const InstrumentItem*)>& accept) const;

    InstrumentItem* findInstrumentItemById(const QString& instrumentId) const;
    bool instrumentExists(const QString& instrumentId) const;

    QString suggestInstrumentName(const QString& baseName) const;
    QStringList instrumentNames() const;

    int selectedIndex() const { return m_selectedIndex; }
    void setSelectedIndex(int newIndex) { m_selectedIndex = newIndex; }

private:
    SelectionProperty<InstrumentItemCatalog>& addEmptyInstrumentSelection();
    SelectionVector<InstrumentItemCatalog> m_instruments;
    int m_selectedIndex = -1;
};

#endif // BORNAGAIN_GUI_MODEL_DEVICE_INSTRUMENTMODEL_H
