//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Item/ItemStackPresenter.h
//! @brief     Defines class ItemStackPresenter
//!
//! @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_VIEW_ITEM_ITEMSTACKPRESENTER_H
#define BORNAGAIN_GUI_VIEW_ITEM_ITEMSTACKPRESENTER_H

#include "Base/Util/Assert.h"
#include "GUI/View/Item/ItemStackWidget.h"
#include <QMap>
#include <QStackedWidget>

//! Operates with item editor of type T, while still keeping signal/slots alive (?)

template <class T>
class ItemStackPresenter : public ItemStackWidget {
public:
    ItemStackPresenter(bool single_widget = false)
        : m_single_widget(single_widget)
    {
    }

    //! Shows the widget for given item (and hides previous one).
    //! If no widget yet exists, it will be created.
    void setItem(QObject* item, QObject* model = nullptr);

    T* itemWidget(QObject* item);

private:
    QMap<QObject*, T*> m_itemToWidget;
    bool m_single_widget; //!< Different items will be served by same widget
};

//... Implementation.

template <class T>
void ItemStackPresenter<T>::setItem(QObject* item, QObject* model)
{
    if (!item) {
        hideWidgets();
        return;
    }

    T* widget = itemWidget(item);

    if (!widget) {
        widget = new T();
        m_stackedWidget->addWidget(widget);
        m_itemToWidget[item] = widget;
    }

    m_stackedWidget->setCurrentWidget(widget);
    if (widget->isHidden())
        widget->show();

    widget->setModel(model);
    widget->setJobOrRealItem(item);
}

template <class T>
T* ItemStackPresenter<T>::itemWidget(QObject* item)
{
    if (m_single_widget) {
        if (!m_itemToWidget.empty())
            return m_itemToWidget.first();
        return nullptr;
    }

    return m_itemToWidget[item];
}

#endif // BORNAGAIN_GUI_VIEW_ITEM_ITEMSTACKPRESENTER_H
