#ifndef RANGESLIDER_H
#define RANGESLIDER_H

#include "qad_widgets_export.h"

#include <QMouseEvent>
#include <QPainter>
#include <QWidget>


class QAD_WIDGETS_EXPORT RangeSlider: public QWidget {
	Q_OBJECT
	Q_FLAGS(Mode)
	Q_PROPERTY(int minimum READ minimum WRITE setMinimum NOTIFY minimumChanged)
	Q_PROPERTY(int maximum READ maximum WRITE setMaximum NOTIFY maximumChanged)
	Q_PROPERTY(int lowerValue READ lowerValue WRITE setLowerValue NOTIFY lowerValueChanged)
	Q_PROPERTY(int upperValue READ upperValue WRITE setUpperValue NOTIFY upperValueChanged)
	Q_PROPERTY(Mode mode READ mode WRITE setMode NOTIFY modeChanged)

public:
	enum ModeEnum {
		NoHandle      = 0x0,
		LeftHandle    = 0x1,
		RightHandle   = 0x2,
		DoubleHandles = LeftHandle | RightHandle
	};
	Q_DECLARE_FLAGS(Mode, ModeEnum)

	RangeSlider(QWidget * parent = Q_NULLPTR);
	RangeSlider(Qt::Orientation ori, Mode m = DoubleHandles, QWidget * parent = Q_NULLPTR);


	int minimum() const { return m_minimum; }
	int maximum() const { return m_maximum; }
	int lowerValue() const { return m_lowerValue; }
	int upperValue() const { return m_upperValue; }
	QPair<int, int> value() const { return QPair<int, int>(m_lowerValue, m_upperValue); }
	Mode mode() const { return m_mode; }

protected:
	QSize minimumSizeHint() const override;
	void paintEvent(QPaintEvent *) override;
	void mousePressEvent(QMouseEvent * e) override;
	void mouseMoveEvent(QMouseEvent * e) override;
	void mouseReleaseEvent(QMouseEvent *) override;
	void changeEvent(QEvent * e) override;

	QRectF firstHandleRect() const;
	QRectF secondHandleRect() const;
	QRectF handleRect(int value) const;

signals:
	void lowerValueChanged(int value);
	void upperValueChanged(int value);
	void valueChanged(int lower_value, int upper_value);
	void rangeChanged(int min, int max);
	void minimumChanged(int minimum);
	void maximumChanged(int maximum);
	void modeChanged(Mode m);

public slots:
	void setLowerValue(int value);
	void setUpperValue(int value);
	void setMinimum(int minimum);
	void setMaximum(int maximum);
	void setRange(int minimum, int maximum);
	void setMode(Mode m);

private:
	Q_DISABLE_COPY(RangeSlider)
	float currentPercentage();
	int validLength() const;
	int interval() const;
	void init();

	int m_minimum;
	int m_maximum;
	int m_lowerValue;
	int m_upperValue;
	bool mFirstHandlePressed;
	bool mSecondHandlePressed;
	int mDelta;
	Qt::Orientation orientation;
	Mode m_mode;
	int scHandleSideLength;
	int scSliderBarHeight;
	int scLeftRightMargin;
};

Q_DECLARE_OPERATORS_FOR_FLAGS(RangeSlider::Mode)

#endif // RANGESLIDER_H
