# ----------------------------------------------------------------------------
#
#  Copyright (C) 2018-2022 Fons Adriaensen <fons@linuxaudio.org>
#    
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http:#www.gnu.org/licenses/>.
#
# ----------------------------------------------------------------------------


from PyQt6 import QtGui, QtCore, QtWidgets
from rotarybase import *


# Linear control, v0...v1 in ns steps.
#
class Rlinctl (RotaryBase):

    def __init__(self, parent, style, v0, v1, ns, dk):
        self.v0 = v0
        self.dv = v1 - v0
        self.ns = ns
        self.dk = dk
        super (Rlinctl, self).__init__(parent, style)
        
    def handle_wheel (self, dw):
        sh = self.modifiers ==  QtCore.Qt.KeyboardModifier.ShiftModifier
        if sh: dk = 1
        else:  dk = self.dk
        if dw < 0: dk = -dk
        self.k = max (0, min (self.ns, self.k + dk))
        
    def handle_move (self, dk):
        if self.mousebutt == QtCore.Qt.MouseButton.LeftButton:
            self.k = max (0, min (self.ns, self.kref + dk // 2))
        
    def k2a (self, k):
        return 225 - 270 * k / self.ns

    def k2v (self, k):
        return self.v0 + self.dv * k / self.ns
        
    def v2k (self, v):
        r = (v - self.v0) / self.dv
        return max (0, min (self.ns, int (self.ns * r)))


# Audio gain control
#
class Rgainctl (RotaryBase):

    def __init__(self, parent, style):
        super (Rgainctl, self).__init__(parent, style)
        
    def handle_wheel (self, dw):
        sh = self.modifiers == QtCore.Qt.KeyboardModifier.ShiftModifier 
        if sh: dk = 1   # 0.5 dB
        else:  dk = 4   # 2.0 dB
        if dw < 0: dk = -dk
        self.k = max (0, min (120, self.k + dk))
        
    def handle_move (self, dk):
        if self.mousebutt == QtCore.Qt.MouseButton.LeftButton:
            self.k = max (0, min (120, self.kref + dk // 2))
        
    def k2a (self, k):
        return 225 - 270 * k / 120

    def k2v (self, k):
        if k > 0: return k / 2 - 50.0
        else:     return -200.0
        
    def v2k (self, v):
        return max (0, min (160, int (2 * v + 100.5)))

