import questionary
import os
from Grifo_E_1553lib.connection.utils import *
from Grifo_E_1553lib.messages.messages import *
from Grifo_E_1553lib.data_types.enums import TargetHistory, RdrModes, StbySelection
from Grifo_E_1553lib.data_types.rdr_mode_command import RdrModeCommandWord
from questionary import Choice

import Grifo_E_1553lib.data_types.enum_map as em

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def submenu(send):
    while not STOP_ALL.is_set():
        sel = questionary.select(
            "Sottomenù - scegli un'opzione:",
            choices=[
                Choice(' - '+msg.label, value=msg.message)
                for msg in MessageDB.getAllMessages().values()
                # for item in sublist
                if isA(msg) == send
            ] + ["Back"]
        ).ask()
        # sel = questionary.select(
        #     "Sottomenù - scegli un'opzione:",
        #     choices=[
        #         Choice(' - '+item.__class__.__name__, value=item.message)
        #         for sublist in MajorFrame.get_majorFrame().values()
        #         for item in sublist
        #         if isA(item) == send
        #     ] + ["Back"]
        # ).ask()
        if sel == "Back" or sel is None:
            return

        submenu_param(sel)

def submenu_param(msg):
    while True:
        sel = questionary.select(
            "Sottomenù - scegli un parametro:",
            choices=[
                Choice(' - '+param,value = {"name" :param, "value" : val}) for param, val in get_tutti_attributi(msg).items()
            ] + ["Back"]
        ).ask()

        if sel == "Back" or sel is None:
            break

        # value = getattr(msg, sel)
        
        enum_class = em.ENUM_MAP.get(sel["name"])

        if enum_class:
            enum_choice = questionary.select(
                f"{sel["name"]} - seleziona valore (attuale: {sel["name"]} = {sel["value"]}):",
                choices=[
                    Choice(f"{'✔ ' if sel["value"] == member else ' - '}{name} = {member.value}", member.value)
                    for name, member in enum_class.__members__.items()
                ] + ["Back"]
            ).ask()

            if enum_choice != "Back" and enum_choice is not None:
                setattr(msg, sel["name"], enum_class(enum_choice))
            continue

        if hasattr(sel["value"], "_fields_") and isinstance(sel["value"]._fields_, list):
            submenu_param(sel["value"])
            continue

        nuovo_valore = questionary.text(
            f"{sel["name"]} - inserisci nuovo valore (attuale: {sel["value"]}) oppure lascia vuoto per annullare:"
        ).ask()

        if nuovo_valore:
            try:
                casted_value = type(sel["value"])(eval(nuovo_valore))
                setattr(msg, sel["name"], casted_value)
            except Exception as e:
                questionary.print(f"Errore nel valore: {e}", style="bold fg:red")


def main_menu():
    while not STOP_ALL.is_set():
        clear_screen()
        sel = questionary.select(
            "Menu principale:",
            choices=["Sent", "Received", "EXIT"]
        ).ask()

        match sel:
            case "Sent":
                submenu(True)
            case "Received":
                submenu(False)
            case "EXIT":
                STOP_ALL.set()
                print("Chiusura del programma.")

def get_tutti_attributi(obj):
    return {
        nome: getattr(obj, nome)
        for nome in dir(obj)
        if not nome.startswith("__") and not nome.startswith("_") and not callable(getattr(obj, nome))
    }

# a1 = A1()
# print(get_tutti_attributi(a1))