//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/coregui/Views/ImportDataWidgets/RealDataTreeModel.h
//! @brief     Defines class RealDataTreeModel
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2021
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_GUI_COREGUI_VIEWS_IMPORTDATAWIDGETS_REALDATATREEMODEL_H
#define BORNAGAIN_GUI_COREGUI_VIEWS_IMPORTDATAWIDGETS_REALDATATREEMODEL_H

#include <QAbstractItemModel>

class RealDataModel;
class RealDataItem;

//! Tree model for real data item selection. Used for the tree in the import view.
class RealDataTreeModel : public QAbstractItemModel {
public:
    void setRealDataModel(RealDataModel* model);

    virtual QModelIndex index(int row, int column,
                              const QModelIndex& parent = QModelIndex()) const override;

    virtual QModelIndex parent(const QModelIndex& index) const override;
    virtual int columnCount(const QModelIndex& parent = QModelIndex()) const override;
    virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override;
    virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
    virtual Qt::ItemFlags flags(const QModelIndex& index) const override;
    virtual bool setData(const QModelIndex& index, const QVariant& value, int role) override;
    RealDataItem* itemForIndex(const QModelIndex& index) const;
    QModelIndex indexForItem(RealDataItem* item) const;

    void refreshAfterModelChange();

    void removeItem(RealDataItem* item);
    RealDataItem* insertSpecularDataItem();
    RealDataItem* insertIntensityDataItem();

    //! The topmost visible item. Can be null of course.
    RealDataItem* topMostItem() const;

private:
    bool isHeadline(const QModelIndex& index) const;
    QModelIndex create1DHeadlineIndex() const;
    QModelIndex create2DHeadlineIndex() const;
    void updateSubsriptions();
    void onContentsProcessed(RealDataItem* item);
    void clear();

private:
    RealDataModel* m_model = nullptr;
    QVector<RealDataItem*> m_items1D; //< Items borrowed from realDataModel. Never delete the ptrs!
    QVector<RealDataItem*> m_items2D; //< Items borrowed from realDataModel. Never delete the ptrs!
    bool m_intermediate1DHeadline = false; //< intermediate state while inserting/removing items
    bool m_intermediate2DHeadline = false; //< intermediate state while inserting/removing items
};

#endif // BORNAGAIN_GUI_COREGUI_VIEWS_IMPORTDATAWIDGETS_REALDATATREEMODEL_H
