import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src')))
import threading
from pynput.keyboard import Key, Listener
from Grifo_E_1553lib.data_types.enums import TargetHistory, RdrModes
from Grifo_E_1553lib.connection.utils import *
from Grifo_E_1553lib.messages.messages import *
# import gui



def start():
    
    print("LIB STARTED.")

    # a1 = A1()
    # a1.message.settings.set_history_level(TargetHistory.TARGET_HISTORY_LEVEL_04)
    # a1.message.settings.str.rdr_symbology_intensity = 127
    # a2 = A2()
    # a2.message.rdr_mode_command.set_master_mode(RdrModes.RWS)
    # a2.message.param1.set_gm_submode(0)

    # # a3 = A3()

    # a4 = A4()
    # a4.message.validity_and_slew.raw = 0

    b6 = MessageNew("B6",MsgRdrSettingsAndParametersTellback,10,16,True)
    b7 = MessageNew("B7",MsgRdrStatusTellback,25,17,True)
    # B1: TWS Status and Targets (request)
    try:
        from Grifo_E_1553lib.messages.tws_status_and_targets import TwsStatusAndTargets0102
        b1 = MessageNew("B1", TwsStatusAndTargets0102, 10, 11, True)
    except Exception:
        b1 = None
    # B2: placeholder using same structure (subAddr 12)
    try:
        b2 = MessageNew("B2", TwsStatusAndTargets0102, 10, 12, True)
    except Exception:
        b2 = None
    # B3: placeholder using same structure (subAddr 13)
    try:
        b3 = MessageNew("B3", TwsStatusAndTargets0102, 10, 13, True)
    except Exception:
        b3 = None
    # B4: placeholder using same structure (subAddr 14)
    try:
        b4 = MessageNew("B4", TwsStatusAndTargets0102, 10, 14, True)
    except Exception:
        b4 = None
    # B5..B18 placeholders (subAddr 15..28)
    try:
        b5 = MessageNew("B5", TwsStatusAndTargets0102, 10, 15, True)
    except Exception:
        b5 = None
    try:
        b8 = MessageNew("B8", TwsStatusAndTargets0102, 10, 18, True)
    except Exception:
        b8 = None
    try:
        b9 = MessageNew("B9", TwsStatusAndTargets0102, 10, 19, True)
    except Exception:
        b9 = None
    try:
        b10 = MessageNew("B10", TwsStatusAndTargets0102, 10, 20, True)
    except Exception:
        b10 = None
    try:
        b11 = MessageNew("B11", TwsStatusAndTargets0102, 10, 21, True)
    except Exception:
        b11 = None
    try:
        b12 = MessageNew("B12", TwsStatusAndTargets0102, 10, 22, True)
    except Exception:
        b12 = None
    try:
        b13 = MessageNew("B13", TwsStatusAndTargets0102, 10, 23, True)
    except Exception:
        b13 = None
    try:
        b14 = MessageNew("B14", TwsStatusAndTargets0102, 10, 24, True)
    except Exception:
        b14 = None
    try:
        b15 = MessageNew("B15", TwsStatusAndTargets0102, 10, 25, True)
    except Exception:
        b15 = None
    try:
        b16 = MessageNew("B16", TwsStatusAndTargets0102, 10, 26, True)
    except Exception:
        b16 = None
    try:
        b17 = MessageNew("B17", TwsStatusAndTargets0102, 10, 27, True)
    except Exception:
        b17 = None
    try:
        b18 = MessageNew("B18", TwsStatusAndTargets0102, 10, 28, True)
    except Exception:
        b18 = None
    # print(MessageDB.getAllMessages())
    # print(b7.label)
    # exit()

    # a1 = A1()
    a1 = MessageNew("A1",MsgRdrSettingsAndParameters,10,1)
    a1.message.settings.set_history_level(TargetHistory.TARGET_HISTORY_LEVEL_04)
    a1.message.settings.str.rdr_symbology_intensity = 127
    # a2 = A2()
    a2 = MessageNew("A2",MsgRdrOperationCommand,25,2)
    a2.message.rdr_mode_command.set_master_mode(RdrModes.RWS)
    a2.message.param1.set_gm_submode(0)
    a2.message.param2.set_spare_0_4(0)
    # a3 = A3()
    print(MessageDB.getMessage("A2"))
    a3 = MessageNew("A3",MsgGraphicSetting,10,3)

    print(a3.head.cw.raw)
    print(a3.size)

    # a4 = A4()
    a4 = MessageNew("A4",MsgNavDataAndCursor,50,4)
    a4.message.validity_and_slew.raw = 0

    # a5 = A5()
    a5 = MessageNew("A5",MsgInuHighSpeed,50,5)
    a5.message.timetag.raw = 0

    # Data-link targets A7 / A8
    a7 = MessageNew("A7", Msg1DataLinkTarget, 20, 7)
    a8 = MessageNew("A8", Msg2DataLinkTarget, 20, 8)






    # print(isA(a2), isA(a4), isA(a5))

    # b1 =Message(TwsStatusAndTargets0102,11, True)
    # b1 =Message(TwsStatusAndTargets0102,11, True)

    # print(vars(RdrModes))
    # print(list(RdrModes)[1].name + " = " + str(list(RdrModes)[1].value))

    # def send_frame_at_right_time(stop, canSend):
    #     print("Sending frames...")
    #     while not stop.is_set():
    #         for key in MajorFrame.get_majorFrame().keys():
    #             if current_milli_time() % key == 0 and canSend.is_set():
    #                 A5().update_A5_time()
    #                 udp_msg = prepare_udp_message(MajorFrame.get_majorFrame()[key])
    #                 send_udp_msg(udp_msg)


    def listen_for_command():
        with Listener(on_press = keypressed) as listener:   
            listener.join()

    canSend.set()

    guii = True

    t1 = threading.Thread(target = MajorFrame.send_frame_at_right_time_new, args=[STOP_ALL,canSend])
    t2 = threading.Thread(target=recv_messages)
    # t3 = threading.Thread(target=gui.main_menu) if guii else None
    # t4 = threading.Thread(target=listen_for_command)

    t1.start()
    t2.start()
    # t3.start() if guii else None
    # t4.start()

    # while not STOP_ALL.is_set():
    #     # udp_msg = prepare_udp_message([a5])
    #     # send_udp_msg(udp_msg)
    #     # print(f"Size of A5: {ctypes.sizeof(MsgInuHighSpeed)}")
    #     # print("PREPARE")
    #     print(isA(b1))
    #     udp_msg = prepare_udp_message([b1])
    #     print("Send")
        
    #     send_udp_msg(udp_msg)
    #     time.sleep(3)
    # # print(RdrModes.__dict__.items())
    # # def stampa_class_constants(cls):
    # #     for name, value in cls.__dict__.items():
    # #         if not name.startswith("__") and not callable(value):
    # #             print(f"{name} = {value}")
    # # stampa_class_constants(RdrModes)



    t1.join()
    t2.join()
    # t3.join()
    # t4.join()

    print("Program Terminated.")
