"""
Menüsystem für Konfiguration(en)

"""

class MenuItem():

    def __init__(self, valtype, label, value=None, unit=''):
        validtypes = ('int', 'bool')
        valtype = valtype.lower() # Groß- und Kleinschreibung lassen wir gemischt zu
        if valtype not in validtypes:
            raise TypeError(f"Invalid value type: '{valtype}'. Only supported: {validtypes}")
        self.label = label # Anzeigetext des Menüeintrag
        self.value = value # Zugeordneter Wert für diesen Eintrag
        self.unit = unit
        self._type = valtype
        self._min = 0
        self._max = 99999
        self.steps = (1, 10, 100, 1000) # Sprungmöglichkeiten für +/- Tasten
        self.step = 0 # index into tuple above
        self.position = None # Menüposition gezählt von 0 an

    def setRange(self, valmin, valmax, steps):
        self.min = valmin
        self.max = valmax
        self.steps = steps

    def setValue(self, val):
        if self._type == 'int':
            if val >= self._min and val <= self._max:
                self.value = val
                return True
        elif self.type == 'bool':
            self.value = val
            return True
        return False

class Menu():

    def __init__(self, title, x, y):
        self.title = title
        self.items = {} # Items über Schlüssel zugreifbar 
        self.activeitem = -1 # Noch nichts aktiv
        self._x = x
        self._y = y
        self._w = 100
        self._h = 20
        self._index = [] # Mapping zwischen Index(Position) und Schlüssel
        self._iter_index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._iter_index < len(self.items):
            itm = self.items[self._index[self._iter_index]]
            self._iter_index += 1
            return itm
        self._iter_index = 0
        raise StopIteration

    def addItem(self, key, label, valtype, value=None, unit=''):
        if key in self.items.keys():
            raise KeyError(f"Duplicate menu item key: '{key}'")
        itm = MenuItem(valtype, label, value, unit)
        self.items[key] = itm
        self._index.append(key)
        itm.position = self._index.index(key)
        return itm

    def setItemActive(self, key):
        self.activeitem = self._index.index(key)

    def getActiveItem(self):
        return self.items[self._index[self.activeitem]]

    def getItemByIndex(self, index):
        return self.items[self._index[index]]

    def getItemByKey(self, key):
        return self.items[key]

    def getItemCount(self):
        return len(self.items)

    def setItemDimension(self, w, h):
        self._w = w
        self._h = h

    def getXY(self):
        return (self._x, self._y)

    def getRect(self):
        return (self._x, self._y, self._w, self._h * len(self.items))

    def getItemRect(self, index):
        y = self._y + index * self._h
        return (self._x, y, self._w, self._h)
