#ifndef SEGMENTSTIMELINE_H
#define SEGMENTSTIMELINE_H

#include <QWidget>
#include <QPainter>
#include <QDebug>
#include <QPaintEvent>
#include <QMouseEvent>
#include <algorithm>

namespace Ui {
class SegmentsTimeline;
}

class SegmentsTimeline : public QWidget
{
    Q_OBJECT

public:
    class Segment {
    private:
        int start;
        int end;
        double length;
        QColor color;
        void *data;

    public:
        Segment(int start, int end, QColor color, void *data);
        int getStart() const;
        int getEnd() const;
        double getLength() const;
        QColor getColor() const;
        void setData(void *data);
        void *getData() const;
        bool operator<(const Segment & second) const;
    };

    typedef std::vector<Segment> Segments;

public:
    explicit SegmentsTimeline(QWidget *parent = 0);
    void setSegments(Segments newSegments = Segments());
    void clearSegments();
    void setHighlightSegments(bool doHighlightSegments);
    void setCursorVisible(bool cursorVisible);
    void setCursorPositionGlobal(double positionGlobal);
    void setCursorPositionSegment(int segmentIdx, double positionSegment);
    ~SegmentsTimeline();

signals:
    void cursorMoved(int segmentIdx, double positionSegment, double positionGlobal);
    void segmentClicked(int segmentIdx, double positionSegment, double positionGlobal);
    
private:
    Ui::SegmentsTimeline *ui;
    Segments segments;
    bool highlightSegments;

    double totalLength;
    double scale;

    double cursorPosition;
    bool cursorGrabbed;
    bool cursorVisible;

    void recomputeDimensions();
    double getScale() const;
    bool isCursorNear(int x, int y, int neighbourhood) const;
    int getCursorPositionPx() const;
    int getSegmentIdxByPosition(double position, double *positionInsideSegment = NULL);

    void paintEvent(QPaintEvent *e);
    void paintSegments(QPainter & painter);
    void paintCursor(QPainter & painter);

    void mouseMoveEvent(QMouseEvent *e);
    void mousePressEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);
    void mouseClickEvent(QMouseEvent *e);
};

#endif // SEGMENTSTIMELINE_H
