//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Numeric/ComboUtil.h
//! @brief     Declares combo functions in namespace GUI::Util, implements templated function.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2022
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_GUI_VIEW_NUMERIC_COMBOUTIL_H
#define BORNAGAIN_GUI_VIEW_NUMERIC_COMBOUTIL_H

#include "GUI/Model/Descriptor/PolyItem.h"
#include "GUI/View/Base/CustomEventFilters.h"
#include <QComboBox>

class ComboProperty;

namespace GUI::Util {

//! Create a combo box with the information found in a ComboProperty.
//!
//! The combo box will be filled with the available options and will get the found tooltips,
//! the common one and individual for each item. The current text will be just passes to "slot"
//! function.
//!
//! If this combox box resides in a scroll area, we ignore mouse wheel events.
//!
//! The combo can be updated from outside using "updaters" list.
QComboBox* createComboBox(std::function<ComboProperty()> comboFunction,
                          std::function<void(const QString&)> slot, bool inScrollArea,
                          QVector<std::function<void()>>* updaters = nullptr, QString tooltip = "");

//! Create a combo box with the information found in a selection property.
//!
//! The combo will be filled with the available options and will get the found tooltip.
//! The current index will be set according to the current index in the selection.
//! Furthermore, the combo box can prohibit accidental changes by the mouse wheel. Otherwise it
//! would be dangerous if the combo is on a scrollable form - unintended and unnoticed changes would
//! take place when just scrolling through the form.
//!
//! Changes in the combobox will be notified to the PolyItem already. The additional (and
//! optional) slot can be used to be notified about an already executed change.
template <typename T> QComboBox*
createComboBoxFromProperty(PolyItem<T>& d, std::function<void(int)> slot, bool inScrollArea)
{
    auto* combo = new QComboBox;
    combo->addItems(d.options());
    combo->setMaxCount(d.options().size());
    combo->setToolTip(d.tooltip());
    combo->setCurrentIndex(d.currentIndex());

    if (inScrollArea)
        WheelEventEater::install(combo);

    QObject::connect(combo, &QComboBox::currentIndexChanged, [&d, slot](int index) {
        d.setCurrentIndex(index);
        if (slot)
            slot(index);
    });

    return combo;
}

} // namespace GUI::Util

#endif // BORNAGAIN_GUI_VIEW_NUMERIC_COMBOUTIL_H
