# -*- coding: utf-8 -*-

# horizontalslider.py
# This file is part of Oqapy
# see: http://bazaar.launchpad.net/~vincent-vandevyvre/oqapy/serie-2.0/
#
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2012-2016 Vincent Vande Vyvre
# Licence: GPL3
#
# Define a group of widgets wich contains a button minus, a slider, a button
# plus and a button reset.
# The widget's layout is horizontal.
#
#  [-] [======[]=====] [+] [|<]

from PyQt5 import QtCore, QtGui, QtWidgets


class HorizontalSlider(QtWidgets.QWidget):
    valueChanged = QtCore.pyqtSignal(int)
    def __init__(self, parent=None):
        super(HorizontalSlider, self).__init__(parent)
        self.layout = QtWidgets.QHBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.minus = QtWidgets.QToolButton(self)
        self.minus.setFont(font)
        self.minus.setText(u'-')
        self.slider = QtWidgets.QSlider(self)
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.plus = QtWidgets.QToolButton(self)
        self.plus.setFont(font)
        self.plus.setText(u'+')
        self.reset = QtWidgets.QToolButton(self)
        self.reset.setFont(font)
        self.reset.setText(u'←')
        self.reset.hide()

        self.layout.addWidget(self.minus)
        self.layout.addWidget(self.slider)
        self.layout.addWidget(self.plus)
        self.layout.addWidget(self.reset)

        self.set_range((0, 99))
        self._value = 0
        self._default = 0

        self.minus.clicked.connect(self.decrement_value)
        self.plus.clicked.connect(self.increment_value)
        self.slider.valueChanged.connect(self.on_value_changed)
        self.reset.clicked.connect(self.reset_value)

    def set_range(self, rng):
        self._min = rng[0]
        self._max = rng[1]
        self.slider.setMinimum(rng[0])
        self.slider.setMaximum(rng[1])

    def set_value(self, value):
        self.slider.setValue(value)

    def set_default_value(self, value):
        self._default = value

    def decrement_value(self):
        self._value -= 1
        self.set_value(self._value)

    def increment_value(self):
        self._value += 1
        self.set_value(self._value)

    def on_value_changed(self, val):
        self._value = val
        self.minus.setEnabled(val > self._min)
        self.plus.setEnabled(val < self._max)
        self.valueChanged.emit(val)

    def get_value(self):
        return self._value

    def set_reset_button(self, b, defaut=0):
        self.reset.setVisible(b)
        self._default = defaut

    def reset_value(self):
        self.slider.setValue(self._default)
