//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Numeric/ComboUtil.cpp
//! @brief     Implements combo functions in namespace GUI::Util.
//!
//! @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)
//
//  ************************************************************************************************

#include "GUI/View/Numeric/ComboUtil.h"
#include "GUI/Model/Descriptor/ComboProperty.h"
#include "GUI/View/Numeric/NumWidgetUtil.h"

QComboBox* GUI::Util::createComboBox(std::function<ComboProperty()> comboFunction,
                                     std::function<void(const QString&)> slot, bool inScrollArea,
                                     QVector<std::function<void()>>* updaters, QString tooltip)
{
    auto* combo = new QComboBox;
    combo->addItems(comboFunction().values());
    combo->setMaxCount(comboFunction().values().size());
    combo->setToolTip(tooltip);
    combo->setCurrentText(comboFunction().currentValue());

    if (comboFunction().toolTips().size() == combo->count())
        for (int index = 0; index < combo->count(); index++)
            combo->setItemData(index, comboFunction().toolTips().at(index), Qt::ToolTipRole);

    if (inScrollArea)
        // Ignore mouse wheel events, since they may be meant for scrolling at large.
        WheelEventEater::install(combo);

    QObject::connect(combo, &QComboBox::currentTextChanged, [=] { slot(combo->currentText()); });

    if (updaters)
        (*updaters) << [=] {
            QSignalBlocker b(combo);
            combo->setCurrentText(comboFunction().currentValue());
        };

    return combo;
}
