#include "double_input.h"


double DoubleInput::intToDouble(int value) const {
	return static_cast<double>(value) / _slider_resolution
		* (_max - _min) + _min;
}


int DoubleInput::doubleToInt(double value) const {
	return (value - _min) / (_max - _min) * _slider_resolution;
}


void DoubleInput::onSpinBoxValueChanged(double value) {
	emit valueChanged(value);
	if (_propagate) {
		_propagate = false;
		_slider->setValue(doubleToInt(value));
	} else {
		_propagate = true;
	}
}


void DoubleInput::onSliderValueChanged(int value) {
	if (_propagate) {
		_propagate = false;
		_spin_box->setValue(intToDouble(value));
	} else {
		_propagate = true;
	}
}


DoubleInput::DoubleInput(QObject *parent, double min, double max,
						 double value,
						 int slider_resolution)
	:QObject(parent),
	 _min(min),
	 _max(max),
	 _slider_resolution(slider_resolution),
	 _spin_box(new QDoubleSpinBox()),
	 _slider(new QSlider(Qt::Horizontal)) {
	_spin_box->setRange(_min, _max);
	_spin_box->setValue(value);
	_slider->setMaximum(_slider_resolution);
	_slider->setValue(doubleToInt(value));
	connect(_slider, &QSlider::valueChanged,
			this, &DoubleInput::onSliderValueChanged);
	connect(_spin_box, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
			this, &DoubleInput::onSpinBoxValueChanged);
}


void DoubleInput::setValue(double value) {
	_spin_box->setValue(value);
}
