#!/usr/bin/python
# -*- coding: utf-8 -*-

import globdef as G
from PyQt5 import QtGui, QtCore, QtWidgets
from matrixwin import *
from controls import *


class Delayelm (QtWidgets.QWidget):

    def __init__(self, parent, style, callb, index): 
        super (Delayelm, self).__init__(parent)
        self.resize (G.ELM_XS, G.ELM_YS)
        self.callb = callb
        self.index = index
        R = Rlinctl (self, style, 0, 100, 200, 10)
        R.move (7, 2)
        R.valueEvent.connect (self.value_event)
        R.show ()
        self.delayctl = R
        L = QtWidgets.QLabel (self)
        L.setFont (G.VAL_FONT)
        L.setText ('')
        L.setGeometry (0, 30, G.ELM_XS - 8, 14)
        L.setAlignment (QtCore.Qt.AlignRight)
        self.delaytxt = L

    def redraw (self):
        delay = self.delayctl.get_value ();
        if self.delayctl.get_state () or (delay > 0):
            self.delaytxt.setText ('%5.1f' % (delay,))    
        else:
            self.delaytxt.setText ('')
        
    def value_event (self, args):
        self.redraw ()
        self.callb (self.index, G.ACT_DELAY, args.get_value (), 0)     
            
    def get_state (self):
        return self.delayctl.get_value ()

    def set_state (self, delay, act):        
        if delay is not None:
            self.delayctl.set_value (delay)
        self.delayctl.set_state (1 if act else 0)
        self.redraw ()

        

class Delaymatwin (Matrixwin):

    def __init__(self, parent, nrow, ncol, callb): 
        super (Delaymatwin, self).__init__(parent, nrow, ncol)
        pal = self.palette () 
        bgc = pal.color (pal.Window)
        style = RotaryStyle (11, bgc, [G.FG_N,G.COL5], [G.MK_N, G.COL0])
        self.controls = {}
        y = 1
        for r in range (nrow):
            x = 1
            for c in range (ncol):
                index = (r, c)
                E = Delayelm (self, style, callb, index)  
                E.move (x, y)
                self.controls [index] = E
                x += G.ELM_XS + 1
            y += G.ELM_YS + 1

    def get_state (self, row, col):
        return self.controls [(row, col)].get_value ()
    
    def set_state (self, row, col, delay, act):
        self.controls [(row, col)].set_state (delay, act)
