 # -*- coding:UTF-8 -*-

import json
from PIL import Image,ImageDraw,ImageFont,ImageColor
from picamera import PiCamera
from time import sleep
import math
import time

class RaMenu:

    __visible = False
    __visible_camera = False

    __showMenu = False
    __currentMenuItem = [0]
    __currentMenuType = ["submenu"]

    def __init__(self, Components):
        """
        Initialisiert das RaMenu

        :param Components: RaComponents Element
        :type Components: RaComponents
        """
        self.components = Components
        self.load_menu_from_json("menu.json")
        self.editOption = None
        self.editOptionValue = None
        self.progress = False
        self.progressValue = 81.2345
        self.components.Keypad.registerKeyDown(self.KeyDown)
        self.components.Keypad.registerKeyHold(self.KeyHold)
        self.components.Keypad.registerKeyPress(self.KeyPress)
        self.initOptions()
        

    def initOptions(self):
        """
        Initialisiert und läd die HUD Optionen
        """
        cfg = self.load_json("config.json")

        # Images
        self.__icon_bg = Image.open('img/'+cfg["hud"]["background"]).convert("RGBA")
        self.__icon_text = Image.open('img/menu_text.png').convert("RGBA")

        # Color
        self.__color = self.components.Util.getColor(cfg["hud"]["color_foreground"])
        self.__colorDisabled = self.components.Util.getColor(cfg["hud"]["color_disabled"])
        self.__colorBG = self.components.Util.getColor(cfg["hud"]["color_background"])
        self.__colorBorder = self.components.Util.getColor(cfg["hud"]["color_border"])
        self.__colorProgress = self.components.Util.getColor(cfg["hud"]["color_progress"])

        # Menu Settings
        self.__drawIconMenuText = cfg["hud"]["iconMenu_DrawText"]
        self.__iconMenu_Theme = cfg["hud"]["iconMenu_Theme"]

        # Fonts
        self.__font = ImageFont.truetype("font/"+cfg["hud"]["font"], 16)
        self.__listfont = ImageFont.truetype("font/"+cfg["hud"]["font"], 12)
        self.__fontProgress = ImageFont.truetype("font/"+cfg["hud"]["font"], 24)

        #finalize
        self.iconPath = 'img/'+self.__iconMenu_Theme+"/"


    def load_menu_from_json(self, filename):
        """
        Lädt die Menüstruktur aus einer JSON-Datei.
        
        :param filename: Der Name der JSON-Datei.
        """
        self.menu_structure = self.load_json(filename)

    def load_json(self, filename):
        """
        Lädt die Menüstruktur aus einer JSON-Datei.
        
        :param filename: Der Name der JSON-Datei.
        """
        res=dict()
        with open(filename, "r") as file:
            res = json.load(file)  # Menüstruktur aus JSON laden
        return res


    def isVisible(self):
        return self.__visible


    def DrawHeadline(self, image,draw,Text):
        draw.rectangle([(0,0),127,20], fill =self.__colorBG, outline =self.__colorBorder)

        if isinstance(Text, str):
            _, _, w2, _ = draw.textbbox((0, 0), Text, font=self.__listfont)
            draw.text((126-w2, 4), text=Text, fill = self.__color, font=self.__font)
        elif isinstance(Text, int):
            _, _, w2, _ = draw.textbbox((0, 0), str(Text), font=self.__listfont)
            draw.text((126-w2, 4), text=str(Text), fill = self.__color, font=self.__font)
        elif isinstance(Text, float):
            _, _, w2, _ = draw.textbbox((0, 0), str(Text), font=self.__listfont)
            draw.text((126-w2, 4), text=str(Text), fill = self.__color, font=self.__font)
        elif "DisplayName" in Text:
            _, _, w2, _ = draw.textbbox((0, 0), Text["DisplayName"], font=self.__listfont)
            draw.text((126-w2, 4), text=Text["DisplayName"], fill = self.__color, font=self.__font)
        elif "displayName" in Text:
            _, _, w2, _ = draw.textbbox((0, 0), Text["displayName"], font=self.__listfont)
            draw.text((126-w2, 4), text=Text["displayName"], fill = self.__color, font=self.__font)
        elif "Displayname" in Text:
            _, _, w2, _ = draw.textbbox((0, 0), Text["Displayname"], font=self.__listfont)
            draw.text((126-w2, 4), text=Text["Displayname"], fill = self.__color, font=self.__font)
        elif "displayname" in Text:
            _, _, w2, _ = draw.textbbox((0, 0), Text["displayname"], font=self.__listfont)
            draw.text((126-w2, 4), text=Text["displayname"], fill = self.__color, font=self.__font)


    #def setDisplay(self, display):
    #    self.__display = display


    #def setCamera(self, camera):
    #    self.__camera = camera


    def getFrame_Submenu(self, image, draw):
        print("Draw Icon Menu")
        mnuItem = self.getCurrentMenuItem()
        if "Icon" in mnuItem:
            icon = Image.open(self.iconPath+mnuItem["Icon"]).convert("RGBA")
            image.paste(icon,(0,0,128,128),icon)
        elif "icon" in mnuItem:
            icon = Image.open(self.iconPath+mnuItem["icon"]).convert("RGBA")
            image.paste(icon,(0,0,128,128),icon)

        if self.__drawIconMenuText == True:
            if "DisplayName" in mnuItem:
                _, _, w, h = draw.textbbox((0, 0), mnuItem["DisplayName"], font=self.__font)
                image.paste(self.__icon_text,(0,0,128,128),self.__icon_text)
                draw.text(((128-w)/2, 101), mnuItem["DisplayName"], fill = self.__color, font=self.__font)
            elif "displayName" in mnuItem:
                _, _, w, h = draw.textbbox((0, 0), mnuItem["displayName"], font=self.__font)
                image.paste(self.__icon_text,(0,0,128,128),self.__icon_text)
                draw.text((int((128-w)/2), 101), mnuItem["displayName"], fill = self.__color, font=self.__font)

    def getFrame_ListMenu(self, image, draw):
        print("Draw List Menu")
        mnuItem = self.getCurrentMenuItem()
        mnu = self.getMenuItem(self.__currentMenuItem)
        index = self.__currentMenuItem[-1]
        _, _, w, h = draw.textbbox((0, 0), "abc", font=self.__listfont)
        ci = 0
        print("W/H: "+str(w)+"/"+str(h))

        icon_check = Image.open('img/check_small.png').convert("RGBA")
        icon_cross = Image.open('img/cross_small.png').convert("RGBA")
        icon_default = Image.open('img/default_small.png').convert("RGBA")

        for entry in mnu:
            y_pos = int(((128-h)/2) + ((ci-index)*(h+4)));
            if ci<index:
                y_pos-=10
            elif ci>index:
                y_pos+=10
            if y_pos>-12 and y_pos<128:
                displayText = ""
                if "DisplayName" in entry:
                    displayText = entry["DisplayName"]
                elif "displayName" in entry:
                    displayText = entry["displayName"]

                if ci==index:
                    draw.text((2, y_pos), text=displayText, fill = self.__color, font=self.__font)
                else:
                    draw.text((2, y_pos), text=displayText, fill = self.__colorDisabled, font=self.__listfont)

                if "Option" in entry:
                    val = self.getConfigValue(entry["Option"]["_var"])
                    valS = ""
                    t = "int"
                    if "_type" in entry["Option"]:
                        t = entry["Option"]["_type"]
                    if t=="list":
                        if isinstance(val, str):
                            valS = val
                        elif isinstance(val, int):
                            valS = entry["Option"]["Options"][val]
                        elif isinstance(val, float):
                            valS = str(val)
                        elif isinstance(val, bool):
                            if val==True:
                                valS="On"
                            else:
                                valS="Off"
                    if t=="string":
                        if isinstance(val, str):
                            valS = val
                        elif isinstance(val, int):
                            valS = str(val)
                        elif isinstance(val, float):
                            valS = str(val)
                        elif isinstance(val, bool):
                            if val==True:
                                valS="On"
                            else:
                                valS="Off"
                    if t=="numeric":
                        if isinstance(val, str):
                            valS = val
                        elif isinstance(val, int):
                            valS = str(val)
                        elif isinstance(val, float):
                            valS = str(val)
                        elif isinstance(val, bool):
                            if val==True:
                                valS="1"
                            else:
                                valS="0"
                    if t=="balance":
                        if isinstance(val, str):
                            valS = val
                        elif isinstance(val, int):
                            valS = str(val)
                        elif isinstance(val, float):
                            valS = str(val)
                        elif isinstance(val, bool):
                            if val==True:
                                valS="1"
                            else:
                                valS="0"
                    if t=="check":
                        if isinstance(val, str):
                            valS = val==""
                        elif isinstance(val, int):
                            valS = val>0
                        elif isinstance(val, float):
                            valS = val>0
                        elif isinstance(val, bool):
                            valS=val
                            
                    if val==None:
                        image.paste(icon_default,(110,y_pos),icon_default)
                    elif isinstance(valS, bool):
                        if valS==True:                                    
                            image.paste(icon_check,(110,y_pos),icon_check)
                        else:
                            image.paste(icon_cross,(110,y_pos),icon_cross)
                    else:
                        _, _, w2, _ = draw.textbbox((0, 0), valS, font=self.__listfont)
                        if ci==index:
                            draw.text((126-w2, y_pos), text=valS, fill = self.__color, font=self.__font)
                        else:
                            draw.text((126-w2, y_pos), text=valS, fill = self.__colorDisabled, font=self.__listfont)

            ci+=1

    def getFrame_OptionList(self, image, draw):
        print("Draw Option List")
        mnuItem = self.getCurrentMenuItem()
        mnu = self.getMenuItem(self.__currentMenuItem)
        index = self.editOptionValue
        val = self.getConfigValue(self.editOption)
                
        _, _, w, h = draw.textbbox((0, 0), "abc", font=self.__listfont)
        ci = 0

        for optK,optV in mnuItem["Option"]["Options"].items():
            #y_pos = int(((128-h)/2) + ((ci-index)*(2+4)));
            y_pos = int(((128-h)/2) + ((ci-index)*(h+4)));
            if ci<index:
                y_pos-=10
            elif ci>index:
                y_pos+=10
            if y_pos>-12 and y_pos<128:
                if ci==index:
                    draw.text((10, y_pos), text=optK, fill = self.__color, font=self.__font)
                else:
                    draw.text((10, y_pos), text=optK, fill = self.__colorDisabled, font=self.__listfont)
            ci+=1

        self.DrawHeadline(image,draw,mnu)

    def getFrame_NumericOption(self,image,draw):
        print("Draw Numeric Option")
        mnu = self.getMenuItem(self.__currentMenuItem)
        mnuItem = self.getCurrentMenuItem()
        index = self.__currentMenuItem[-1]
        _min = mnuItem["Option"]["_min"]
        _max = mnuItem["Option"]["_max"]
        val = self.editOptionValue

        draw.rectangle([(108,22),(124,126)],outline =self.__color)
        barHeight = 100
        progress = barHeight - (((val - _min) / (_max - _min)) * barHeight)
        draw.rectangle([(110,24+progress),(122,124)],fill =self.__color)

        _, _, w, h = draw.textbbox((0, 0), str(val), font=self.__font)
        pos_x = (120-w)/2
        draw.text((pos_x, int((128-h)/2)), text=str(val), fill = self.__color, font=self.__font)

        #imgUp = Image.open('img/numUp.png').convert("RGBA")
        #imgDown = Image.open('img/numDown.png').convert("RGBA")
        #image.paste(imgUp,(30,int(((128-h)/2)-h)),imgUp)
        #image.paste(imgDown,(30,int(((128-h)/2)+h+h)),imgDown)


        trianglePosY = int(((128-h)/2)-h)
        draw.polygon([(30,trianglePosY+10), (pos_x, trianglePosY), (pos_x+(pos_x-30),trianglePosY+10)], fill = self.__color)

        trianglePosY = int(((128-h)/2)+h+h)
        draw.polygon([(30,trianglePosY), (pos_x, trianglePosY+10), (pos_x+(pos_x-30),trianglePosY)], fill = self.__color)

        self.DrawHeadline(image,draw,mnu)

    def getFrame_BalanceOption(self,image,draw):
        print("Draw Balance Option")
        mnu = self.getMenuItem(self.__currentMenuItem)
        mnuItem = self.getCurrentMenuItem()
        index = self.__currentMenuItem[-1]
        _min = mnuItem["Option"]["_min"]
        _max = mnuItem["Option"]["_max"]
        val = self.editOptionValue

        draw.rectangle([(108,22),(124,126)],outline =self.__color)
        barHeight = 96
        progress = barHeight - (((val - _min) / (_max - _min)) * barHeight)
        draw.rectangle([(110,22+progress),(122,26+progress)],fill =self.__color)

        _, _, w, h = draw.textbbox((0, 0), str(val), font=self.__font)
        pos_x = (120-w)/2
        draw.text((pos_x, int((128-h)/2)), text=str(val), fill = self.__color, font=self.__font)

        #imgUp = Image.open('img/numUp.png').convert("RGBA")
        #imgDown = Image.open('img/numDown.png').convert("RGBA")
        #image.paste(imgUp,(30,int(((128-h)/2)-h)),imgUp)
        #image.paste(imgDown,(30,int(((128-h)/2)+h+h)),imgDown)

        trianglePosY = int(((128-h)/2)-h)
        draw.polygon([(30,trianglePosY+10), (pos_x, trianglePosY), (pos_x+(pos_x-30),trianglePosY+10)], fill = self.__color)

        trianglePosY = int(((128-h)/2)+h+h)
        draw.polygon([(30,trianglePosY), (pos_x, trianglePosY+10), (pos_x+(pos_x-30),trianglePosY)], fill = self.__color)

        self.DrawHeadline(image,draw,mnu)
        


    def getFrame_Progress(self, image,draw):
        progressValue = self.progressValue
        
        if progressValue==-1:
            pos=(time.time() * 130) % 360
            draw.ellipse((31,31,97,97), fill=self.__colorDisabled)
            draw.pieslice((30, 30, 98, 98), start=pos, end=pos+80, fill=self.__colorProgress)
            draw.ellipse((35,35,93,93), fill=self.__colorBG)
            draw.ellipse((37,37,91,91), fill=self.__colorBG)
        else:
            draw.ellipse((31,31,97,97), fill=self.__colorDisabled)
            draw.pieslice((30, 30, 98, 98), start=-90, end=int(progressValue*3.6)-90, fill=self.__colorProgress)
            draw.ellipse((35,35,93,93), fill=self.__colorBG)
            draw.ellipse((37,37,91,91), fill=self.__colorBG)
            _, _, w, h = draw.textbbox((0, 0), str(math.floor(progressValue))+" %", font=self.__fontProgress)
            draw.text(((128-w) / 2, (128-h)/2), text=str(math.floor(progressValue))+" %", fill = self.__colorProgress, font=self.__fontProgress)

    def getFrame(self):
        if self.__visible == True:

            image = Image.new("RGBA", (128, 128), self.__colorBG)
            draw = ImageDraw.Draw(image)
            image.paste(self.__icon_bg,(0,0,128,128),self.__icon_bg)

            if self.__currentMenuType[-1]=="submenu":
                self.getFrame_Submenu(image, draw)
                
            elif self.__currentMenuType[-1]=="listmenu":
                self.getFrame_ListMenu(image,draw)

            elif self.__currentMenuType[-1]=="options":
                self.getFrame_OptionList(image,draw)

            elif self.__currentMenuType[-1]=="numeric":
                self.getFrame_NumericOption(image,draw)

            elif self.__currentMenuType[-1]=="balance":
                self.getFrame_BalanceOption(image,draw)

            if self.progress == True:
                time.sleep(0.1)
                self.getFrame_Progress(image,draw)
            else:
                time.sleep(0.3)

            return image
        return False

    def getConfigValue(self, path, default=None):
        if self.config == None:
            self.config = self.load_json("config.json")
        return self.getObjValue(self.config, path, 0, default)
        #pathes = path.split(".")
        #if len(pathes)==10:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]][pathes[9]]
        #elif len(pathes)==9:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]]
        #elif len(pathes)==8:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]]
        #elif len(pathes)==7:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]]
        #elif len(pathes)==6:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]]
        #elif len(pathes)==5:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]]
        #elif len(pathes)==4:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]]
        #elif len(pathes)==3:
        #    return self.config[pathes[0]][pathes[1]][pathes[2]]
        #elif len(pathes)==2:
        #    return self.config[pathes[0]][pathes[1]]
        #elif len(pathes)==1:
        #    return self.config[pathes[0]]

    def getObjValue(self,obj,path,index, default):
        pathes = path.split(".")
        if index==len(pathes):
            return obj
        else:
            if pathes[index] in obj:
                return self.getObjValue(obj[pathes[index]],path,index+1, default)
            else:
                return default

    def setConfigValue(self, path, value):
        pathes = path.split(".")
        if self.config == None:
            self.config = self.load_json("config.json")
        if value == None:
            if len(pathes)==10:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]][pathes[9]]
            elif len(pathes)==9:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]]
            elif len(pathes)==8:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]]
            elif len(pathes)==7:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]]
            elif len(pathes)==6:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]]
            elif len(pathes)==5:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]]
            elif len(pathes)==4:
                del self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]]
            elif len(pathes)==3:
                del self.config[pathes[0]][pathes[1]][pathes[2]]
            elif len(pathes)==2:
                del self.config[pathes[0]][pathes[1]]
            elif len(pathes)==1:
                del self.config[pathes[0]]
        else:
            if len(pathes)==10:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]][pathes[9]] = value
            elif len(pathes)==9:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]][pathes[8]] = value
            elif len(pathes)==8:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]][pathes[7]] = value
            elif len(pathes)==7:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]][pathes[6]] = value
            elif len(pathes)==6:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]][pathes[5]] = value
            elif len(pathes)==5:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]][pathes[4]] = value
            elif len(pathes)==4:
                self.config[pathes[0]][pathes[1]][pathes[2]][pathes[3]] = value
            elif len(pathes)==3:
                self.config[pathes[0]][pathes[1]][pathes[2]] = value
            elif len(pathes)==2:
                self.config[pathes[0]][pathes[1]] = value
            elif len(pathes)==1:
                self.config[pathes[0]] = value
        with open("config.json", "w") as outfile:
            outfile.write(json.dumps(self.config))

    def getMenuItem(self, index):
        return self.__getMenuItemSub(self.menu_structure,index, 0)

    def getCurrentMenuItem(self):
        mnu = self.__getMenuItemSub(self.menu_structure, self.__currentMenuItem, 0)
        return mnu[self.__currentMenuItem[-1]]

    def __getMenuItemSub(self, mnu,index,i):
        length = len(index)
        if i<(length-1):
            if "sub" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["sub"],index,i+1)
            elif "Sub" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["Sub"],index,i+1)
            elif "SubMenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["SubMenu"],index,i+1)
            elif "subMenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["subMenu"],index,i+1)
            elif "Submenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["Submenu"],index,i+1)

            elif "list" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["list"],index,i+1)
            elif "List" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["List"],index,i+1)
            elif "ListMenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["ListMenu"],index,i+1)
            elif "listMenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["listMenu"],index,i+1)
            elif "Listmenu" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["Listmenu"],index,i+1)
            
            elif "Option" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["Option"],index,i+1)
            elif "option" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["option"],index,i+1)

            elif "Options" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["Options"],index,i+1)
            elif "options" in mnu[index[i]]:
                return self.__getMenuItemSub(mnu[index[i]]["options"],index,i+1)
        return mnu


    def __executeFunc(self,s : str):
        self.components.Util.Execute(s)

    def KeyDown(self, key):
        if self.__visible == True:
            if key=="KEY_LEFT":
                self.Back()
            if key=="KEY_RIGHT":
                self.Right()
            self.components.Display.RequestUpdate()
        if key=="KEY1":
            if self.components.Camera.isRecording():
                self.components.Camera.stopRecording()
            else:
                self.components.Camera.startRecording()
        if key=="KEY3":
            if self.__visible_camera==True:
                self.__visible_camera = False
            else:
                self.__visible_camera = True
            self.checkDisplayEnabled()

    def KeyHold(self, key, duration):
        if self.__visible == True:
            if key=="KEY_PRESS":
                if duration>=3:
                    self.__visible = False
                    self.checkDisplayEnabled()
            elif key=="KEY_UP":
                self.Up()
            elif key=="KEY_DOWN":
                self.Down()
            self.components.Display.RequestUpdate()

    def KeyPress(self, key, duration):
        if key=="KEY_PRESS":
            if duration<3:
                if self.__visible == True:
                    self.Right()
                else:
                    self.config = self.load_json("config.json")
                    self.__visible = True
                    self.checkDisplayEnabled()
            if self.components.Display is not None:
                self.components.Display.RequestUpdate()

    def checkDisplayEnabled(self):
        if self.__visible_camera == True or self.__visible == True:
            self.components.Display.On()
        else:
            self.components.Display.Off()

    def Back(self):
        if len(self.__currentMenuItem) <= 1:
            self.__visible = False
            self.__currentMenuItem = [0]
            self.__currentMenuType = ["submenu"]
        else:
            self.__currentMenuItem = self.__currentMenuItem[ : -1]
            self.__currentMenuType = self.__currentMenuType[ : -1]

    def Right(self):
        mnuItem = self.getCurrentMenuItem()

        #Save Option Values
        if self.editOption != None and self.__currentMenuType[-1]=="numeric":
            self.setConfigValue(self.editOption, self.editOptionValue)
            self.editOption = None
            self.editOptionValue = None
            self.__currentMenuType = self.__currentMenuType[:-1]
            return
        elif self.editOption != None and self.__currentMenuType[-1]=="balance":
            self.setConfigValue(self.editOption, self.editOptionValue)
            self.editOption = None
            self.editOptionValue = None
            self.__currentMenuType = self.__currentMenuType[:-1]
            return
        elif self.editOption != None and self.__currentMenuType[-1]=="options":
            index = self.editOptionValue
            for optK,optV in mnuItem["Option"]["Options"].items():
                if index==0:
                    self.setConfigValue(self.editOption, optK)
                    break;
                index-=1
            self.editOption = None
            self.editOptionValue = None
            self.__currentMenuType = self.__currentMenuType[:-1]
            return

        if "action" in mnuItem:
            self.__executeFunc(mnuItem["action"])
        elif "Action" in mnuItem:
            self.__executeFunc(mnuItem["Action"])

        if "sub" in mnuItem or "Sub" in mnuItem or "SubMenu" in mnuItem or "subMenu" in mnuItem or "Submenu" in mnuItem:
            self.__currentMenuItem.append(0)
            self.__currentMenuType.append("submenu")

        if "list" in mnuItem or "List" in mnuItem or "ListMenu" in mnuItem or "listMenu" in mnuItem or "Listmenu" in mnuItem:
            self.__currentMenuItem.append(0)
            self.__currentMenuType.append("listmenu")

        if "Option" in mnuItem:
            if "_type" in mnuItem["Option"]:
                if mnuItem["Option"]["_type"]=="list":
                    print("Option Show List")
                    val = self.getConfigValue(mnuItem["Option"]["_var"])
                    self.editOptionValue=0
                    for optK,optV in mnuItem["Option"]["Options"].items():
                        if val==optV:
                            break;
                        self.editOptionValue+=1
                    self.editOption=mnuItem["Option"]["_var"]
                    self.__currentMenuType.append("options")
                elif mnuItem["Option"]["_type"]=="check":
                    val = self.getConfigValue(mnuItem["Option"]["_var"])
                    if isinstance(val, bool):
                        if val==True:
                            print("Option Change: "+mnuItem["Option"]["_var"]+" = False")
                            self.setConfigValue(mnuItem["Option"]["_var"], False)
                        else:
                            print("Option Change: "+mnuItem["Option"]["_var"]+" = True")
                            self.setConfigValue(mnuItem["Option"]["_var"], True)
                    elif isinstance(val, int):
                        if val>1:
                            print("Option Change: "+mnuItem["Option"]["_var"]+" = 0")
                            self.setConfigValue(mnuItem["Option"]["_var"],0)
                        else:
                            print("Option Change: "+mnuItem["Option"]["_var"]+" = 1")
                            self.setConfigValue(mnuItem["Option"]["_var"],1)
                elif mnuItem["Option"]["_type"]=="numeric":
                    print("Option Show Numeric")
                    self.editOption=mnuItem["Option"]["_var"]
                    val = self.getConfigValue(mnuItem["Option"]["_var"])
                    self.editOptionValue=val
                    self.__currentMenuType.append("numeric")
                elif mnuItem["Option"]["_type"]=="balance":
                    print("Option Show Balance")
                    self.editOption=mnuItem["Option"]["_var"]
                    val = self.getConfigValue(mnuItem["Option"]["_var"])
                    self.editOptionValue=val
                    self.__currentMenuType.append("balance")


                    
            

    def Up(self):
        if self.editOption != None and self.__currentMenuType[-1]=="numeric":
            self.editOptionValue+=1
        elif self.editOption != None and self.__currentMenuType[-1]=="balance":
            self.editOptionValue+=1
        elif self.editOption != None and self.__currentMenuType[-1]=="options":
            self.editOptionValue-=1

        elif self.__currentMenuItem[-1]>0:
            self.__currentMenuItem[-1] = self.__currentMenuItem[-1] - 1

    def Down(self):
        if self.editOption != None and self.__currentMenuType[-1]=="numeric":
            self.editOptionValue-=1
        if self.editOption != None and self.__currentMenuType[-1]=="balance":
            self.editOptionValue-=1
        elif self.editOption != None and self.__currentMenuType[-1]=="options":
            self.editOptionValue+=1
        else:
            mnu = self.getMenuItem(self.__currentMenuItem)
            maxMnu = len(mnu) -1
            if self.__currentMenuItem[-1]<maxMnu:
                self.__currentMenuItem[-1] = self.__currentMenuItem[-1] + 1


    def Progress(self, percent:float):
        self.progress = True
        self.progressValue = percent
        self.components.Display.RequestUpdate()
        self.components.Keypad.Enabled(False)

    def StopProgress(self):
        self.progress = False
        self.progressValue = 0.0
        self.components.Display.RequestUpdate()
        self.components.Keypad.Enabled(True)
