/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <QWidget>
#include <QPen>
#include <QBrush>

class QSpinBox;
class MvQRangeWidget;

class MvQRangePlotWidget : public QWidget
{
public:
    MvQRangePlotWidget(MvQRangeWidget*);

protected:
    void paintEvent(QPaintEvent*);
    void mousePressEvent(QMouseEvent*);
    void mouseMoveEvent(QMouseEvent*);
    void mouseReleaseEvent(QMouseEvent*);
    QRect rangeRect();
    QPolygon minDragShape();
    QPolygon maxDragShape();

    enum UserAction
    {
        NoAction,
        MinDragAction,
        MaxDragAction,
        MoveAction
    };
    enum HoverMode
    {
        NoHover,
        MinDragHover,
        MaxDragHover,
        MoveHover
    };

    MvQRangeWidget* parent_{nullptr};
    QPoint dragPos_;
    UserAction action_{NoAction};
    HoverMode hover_{NoHover};
    int offset_{15};
    int dragRadius_{10};
    int dragMin_{0};
    int dragMax_{0};
    QBrush bgBrush_;
    QPen pen_;
    QBrush selectorBrush_;
    QPen selectorPen_;
    QBrush handlerBrush_;
};

class MvQRangeWidget : public QWidget
{
    Q_OBJECT

public:
    MvQRangeWidget(QWidget* parent = 0);

    void setRange(int, int);
    void reset(QVector<float>);
    void adjustRange(int, int, float);
    void adjustRangeStart(int, float);
    void adjustRangeEnd(int, float);
    int rangeStartIndex() const { return rangeStartIndex_; }
    int rangeEndIndex() const { return rangeEndIndex_; }
    float rangeStartPercent() const;
    float rangeEndPercent() const;
    float indexPercent(int) const;
    float startValue();
    float endValue();
    float value(int);
    int valueCount();

public slots:
    void slotStartSpin(int);
    void slotEndSpin(int);
    void slotSelectWholeRange(bool);

signals:
    void valueChanged(int, int);

protected:
    void checkValues();
    void updateSpins();

    QVector<float> values_;
    int rangeStartIndex_{-1};
    int rangeEndIndex_{-1};
    QSpinBox* startSpin_{nullptr};
    QSpinBox* endSpin_{nullptr};
    MvQRangePlotWidget* plot_{nullptr};
    bool ignoreSpinChange_{false};
};
