//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/ParEdit/ParameterTuningDelegate.h
//! @brief     Defines class ParameterTuningDelegate.
//!
//! @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_PAREDIT_PARAMETERTUNINGDELEGATE_H
#define BORNAGAIN_GUI_VIEW_PAREDIT_PARAMETERTUNINGDELEGATE_H

#include "Fit/Param/RealLimits.h"
#include <QItemDelegate>
#include <memory>

class ParSpinBox;
class ParameterItem;
class QHBoxLayout;

//! View and control for parameters in RealTime (or Fit ?) activity.
//! In ParameterTuningWidget attached to the tree view.

class ParameterTuningDelegate : public QItemDelegate {
    Q_OBJECT
public:
    class TuningData {
    public:
        TuningData();
        void setRangeFactor(double range_factor);
        void setItemLimits(const RealLimits& item_limits);
        int value_to_slider(double value);
        double slider_to_value(int slider) const;
        double step() const;
        int m_smin;
        int m_smax;
        double m_rmin;
        double m_rmax;
        double m_range_factor;
        RealLimits m_item_limits;
    };

    ParameterTuningDelegate(QObject* parent = nullptr);
    ~ParameterTuningDelegate() override;

    QSize sizeHint(const QStyleOptionViewItem& option,
                   const QModelIndex& /* index */) const override
    {
        return QSize(option.rect.width(), 25);
    }

    void paint(QPainter* painter, const QStyleOptionViewItem& option,
               const QModelIndex& index) const override;
    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
                          const QModelIndex& index) const override;
    void setEditorData(QWidget* editor, const QModelIndex& index) const override;
    void setModelData(QWidget* editor, QAbstractItemModel* model,
                      const QModelIndex& index) const override;
    void setSliderRangeFactor(int value);

    void setReadOnly(bool isReadOnly);

signals:
    void currentLinkChanged(ParameterItem* item);

private slots:
    void sliderValueChanged(int position);
    void editorValueChanged(double value);

private:
    void updateSlider(double value) const;
    void emitSignals(double value);

    int m_value_column;
    mutable QSlider* m_slider;
    mutable ParSpinBox* m_value_box;
    mutable QHBoxLayout* m_content_layout;
    mutable ParameterItem* m_current_item;
    mutable TuningData m_tuning_info;
    bool m_is_read_only;
};

#endif // BORNAGAIN_GUI_VIEW_PAREDIT_PARAMETERTUNINGDELEGATE_H
