# ----------------------------------------------------------------------------
#
#  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 math import log10
from utils.rotarybase import *


# Logarithmic control, v0...v1 in ns steps.
#
class Rlogctl (RotaryBase):

    def __init__(self, parent, style, v0, v1, ns, dk):
        self.v0 = v0
        self.rv = log10 (v1 / v0)
        self.ns = ns
        self.dk = dk
        super (Rlogctl, 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 * pow (10, self.rv * k / self.ns)
        
    def v2k (self, v):
        k = int (self.ns * log10 (v / self.v0) / self.rv + 0.5)
        return max (0, min (self.ns, k))


# 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)))

