/***************************** 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 *************************************/

#include "MvQSlider.h"

#include <QtGlobal>
#include <QDebug>
#include <QMouseEvent>
#include <QStyle>

MvQSlider::MvQSlider(QWidget* parent) :
    QSlider(parent)
{
}


// There is a bug in QSlider: if we click into
// the slider it does not jump into the right position but either jumps to the
// min or to the max position of the slider. It only works if we keep the mouse pressed down
// at least for 1-2 seconds!!!
//
// To overcome this problem we needed this custom implementation of mousePressEvent!

void MvQSlider::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        int v = 0;
        if (orientation() == Qt::Vertical) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
            v = QStyle::sliderValueFromPosition(minimum(), maximum(), height() - event->position().y(), height());
#else
            v = QStyle::sliderValueFromPosition(minimum(), maximum(), height() - event->y(), height());
#endif
        }
        else {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
            v = QStyle::sliderValueFromPosition(minimum(), maximum(), event->position().x(), width());
#else
            v = QStyle::sliderValueFromPosition(minimum(), maximum(), event->x(), width());
#endif
        }

        if (v == value()) {
            QSlider::mousePressEvent(event);
        }
        else {
            setSliderPosition(v);
            event->accept();
            return;
        }
    }

    QSlider::mousePressEvent(event);
}
