//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Device/ScanRangeForm.cpp
//! @brief     Implement class ScanRangeForm
//!
//! @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)
//
//  ************************************************************************************************

#include "GUI/View/Device/ScanRangeForm.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Axis/BasicAxisItem.h"
#include "GUI/View/Base/CustomEventFilters.h"
#include "GUI/View/Numeric/DSpinBox.h"

ScanRangeForm::ScanRangeForm(QFormLayout* form, QString units)
    : m_axis_item(nullptr)
{
    m_nbins_spin_box = new QSpinBox;
    m_nbins_spin_box->setFocusPolicy(Qt::StrongFocus);
    WheelEventEater::install(m_nbins_spin_box);
    m_nbins_spin_box->setRange(1, 65536);
    connect(m_nbins_spin_box, &QSpinBox::valueChanged, this, &ScanRangeForm::onNbinsValueChanged);
    form->addRow("# scan points:", m_nbins_spin_box);

    m_minimum_spin_box = new DSpinBox(nullptr);
    connect(m_minimum_spin_box, &DSpinBox::valueChanged, this, &ScanRangeForm::onMinValueChanged);
    form->addRow("Initial [" + units + "]:", m_minimum_spin_box);

    m_maximum_spin_box = new DSpinBox(nullptr);
    connect(m_maximum_spin_box, &DSpinBox::valueChanged, this, &ScanRangeForm::onMaxValueChanged);
    form->addRow("Final [" + units + "]:", m_maximum_spin_box);
}

void ScanRangeForm::setAxisItem(BasicAxisItem* axisItem)
{
    ASSERT(axisItem);
    m_axis_item = axisItem;
    setEnabled(m_axis_item);
    updateData();
}

void ScanRangeForm::setEnabled(bool enabled)
{
    m_nbins_spin_box->setEnabled(enabled);
    m_minimum_spin_box->setEnabled(enabled);
    m_maximum_spin_box->setEnabled(enabled);
}

void ScanRangeForm::updateData()
{
    ASSERT(m_axis_item);

    QSignalBlocker b1(m_nbins_spin_box);
    QSignalBlocker b2(m_minimum_spin_box);
    QSignalBlocker b3(m_maximum_spin_box);

    m_nbins_spin_box->setValue(m_axis_item->size());
    m_minimum_spin_box->replaceProperty(&m_axis_item->min());
    m_maximum_spin_box->replaceProperty(&m_axis_item->max());
}

void ScanRangeForm::onNbinsValueChanged(size_t value)
{
    ASSERT(m_axis_item);
    if (m_axis_item->size() == value)
        return;

    m_axis_item->resize(value);
}

void ScanRangeForm::onMinValueChanged(double value)
{
    ASSERT(m_axis_item);

    // update other limit so that min<=max
    if (m_axis_item->max().dVal() < value)
        m_axis_item->max().setAndNotify(value);
}

void ScanRangeForm::onMaxValueChanged(double value)
{
    ASSERT(m_axis_item);

    // update other limit so that min<=max
    if (m_axis_item->min().dVal() > value)
        m_axis_item->min().setAndNotify(value);
}
