from tkinter import *

import tkinter as tk
import Epreuve3 as e3
import subprocess
import sys

root = tk.Tk()
root.title("Simulateur Epreuve 3 - 24H du Code 2026")
image = tk.PhotoImage(file="SII++.png")
#root.configure(bg="#0059A3")
root.configure(bg="#89B4E1")
# Widgets are added here

#Frame principale
frame = tk.Frame(root, width=800, height=400, background="#89B4E1")
frame.pack(padx=10, pady=10)



#Frames Corps
instructions_frame = tk.Frame(frame, width=400, height=400, bg="#89B4E1")
instructions_frame.pack(padx=5, pady=5, side=tk.LEFT, fill=Y)

infos_frames = tk.Frame(frame, width=400, height=400, bg="#89B4E1")
infos_frames.pack(padx=5, pady=5, side=tk.RIGHT)



#Frame stack
stack_frame = tk.Frame(instructions_frame, width=400, height=300)
stack_frame.pack(padx=5, pady=5, side=tk.TOP)

Label(stack_frame, text=f"Stack").pack(pady=5)

scrollbar = tk.Scrollbar(stack_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

mylist = tk.Listbox(stack_frame, yscrollcommand=scrollbar.set, width=50)


mylist.pack(side=tk.LEFT, fill=tk.BOTH)
scrollbar.config(command=mylist.yview)




#Frame instruction suivante
single_inst_frame = tk.Frame(instructions_frame, width=400, height=100, bg="#89B4E1")
single_inst_frame.pack(padx=5, pady=5, side=tk.TOP)


Label(single_inst_frame, text=f"Instruction").pack(pady=5, side=LEFT)
single_instr = Label(single_inst_frame, text=f"instruction+cycle", width=30, bg="white")
single_instr.pack(pady=5, side=tk.LEFT)

image_frame = tk.Frame(instructions_frame, width=400, height=100, bg="#89B4E1")
image_frame.pack(padx=5, pady=5, side=tk.TOP)

display_image = image.subsample(10, 10)
tk.Label(image_frame, image=display_image, bg="#89B4E1").pack(padx=5, pady=5)

#Frame registres
registres_frames = tk.Frame(infos_frames, width=400, height=100, bg="#89B4E1")
registres_frames.pack(padx=10, pady=10, side=tk.TOP)


#Registre 1
registre_1_frame = tk.Frame(registres_frames, width=100, height=100, bg="orange")
registre_1_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(registre_1_frame, text=f"R0", width=15, bg="orange").pack(pady=5)
label_registre_1 = Label(registre_1_frame, bg="orange")
label_registre_1.pack(pady=5)





#Registre 2
registre_2_frame = tk.Frame(registres_frames, width=100, height=100, bg="orange")
registre_2_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(registre_2_frame, text=f"R1", width=15, bg="orange").pack(pady=5)
label_registre_2 = Label(registre_2_frame, bg="orange")
label_registre_2.pack(pady=5)




#Registre 3
registre_3_frame = tk.Frame(registres_frames, width=100, height=100, bg="orange")
registre_3_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(registre_3_frame, text=f"R2", width=15, bg="orange").pack(pady=5)
label_registre_3 = Label(registre_3_frame, bg="orange")
label_registre_3.pack(pady=5)




#Registre 4
registre_4_frame = tk.Frame(registres_frames, width=100, height=100, bg="ORANGE")
registre_4_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(registre_4_frame, text=f"R3", width=15, bg="orange").pack(pady=5)
label_registre_4 = Label(registre_4_frame, bg="orange")
label_registre_4.pack(pady=5)


#Frame annexes
annexes_frames = tk.Frame(infos_frames, width=400, height=100, bg="#89B4E1")
annexes_frames.pack(padx=10, pady=10, side=tk.TOP)


#Annexe 1
annexe_1_frame = tk.Frame(annexes_frames, width=100, height=100, bg="orange")
annexe_1_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(annexe_1_frame, text=f"EQ", width=15, bg="orange").pack(pady=5)
label_eq = Label(annexe_1_frame, bg="orange")
label_eq.pack(pady=5)





#RAnnexe 2
annexe_2_frame = tk.Frame(annexes_frames, width=100, height=100, bg="orange")
annexe_2_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(annexe_2_frame, text=f"LT", width=15, bg="orange").pack(pady=5)
label_lt = Label(annexe_2_frame, bg="orange")
label_lt.pack(pady=5)




#Annexe 3
annexe_3_frame = tk.Frame(annexes_frames, width=100, height=100, bg="orange")
annexe_3_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(annexe_3_frame, text=f"PC", width=15, bg="orange").pack(pady=5)
label_pc = Label(annexe_3_frame, bg="orange")
label_pc.pack(pady=5)




#Annexe 4
annexe_4_frame = tk.Frame(annexes_frames, width=100, height=100, bg="ORANGE")
annexe_4_frame.pack(padx=10, pady=0, side=tk.LEFT)

Label(annexe_4_frame, text=f"SP", width=15, bg="orange").pack(pady=5)
label_sp = Label(annexe_4_frame, bg="orange")
label_sp.pack(pady=5)

#Frame RAM
ram_frame = tk.Frame(infos_frames, width=400, height=100)
ram_frame.pack(padx=10, pady=10, side=tk.TOP)

Label(ram_frame, text=f"RAM").pack(pady=5)

scrollbarRam = tk.Scrollbar(ram_frame)
scrollbarRam.pack(side=tk.RIGHT, fill=tk.Y)

myRamList = tk.Listbox(ram_frame, yscrollcommand=scrollbarRam.set, width=50)


myRamList.pack(side=tk.LEFT, fill=tk.BOTH)
scrollbarRam.config(command=myRamList.yview)


#Frame OUT
out_frame = tk.Frame(infos_frames, width=400, height=100)
out_frame.pack(padx=10, pady=10, side=tk.TOP)

Label(out_frame, text=f"OUT").pack(pady=5)


scrollbarOut = tk.Scrollbar(out_frame)
scrollbarOut.pack(side=tk.RIGHT, fill=tk.Y)

myOutList = tk.Listbox(out_frame, yscrollcommand=scrollbarOut.set, width=50)


myOutList.pack(side=tk.LEFT, fill=tk.BOTH)
scrollbarOut.config(command=myOutList.yview)



#val = subprocess.run(["/usr/bin/python3", "/home/aurelien/Documents/24hducode2026/24H_du_code_2026/Epreuve3.py", "test_bin_epreuve3/call_label.bin"]            # transforme bytes en str)


previous_sp = None  # Initialisation avant la première itération

def update_gui():
    global previous_sp, sim_iter  # Accéder à la variable globale previous_sp
    try:
        state = next(sim_iter)

        # 👉 mise à jour label instruction
        single_instr.config(
            text=state["instr"] + "  Cycle(s): " + str(state["cycles_added"])
        )

        label_registre_1.config(text=f"{state['regs'][0]:02X}")
        label_registre_2.config(text=f"{state['regs'][1]:02X}")
        label_registre_3.config(text=f"{state['regs'][2]:02X}")
        label_registre_4.config(text=f"{state['regs'][3]:02X}")
        label_eq.config(text=f"{state['eq']}")
        label_lt.config(text=f"{state['lt']}")
        label_pc.config(text=f"{state['pc']:02X}")
        label_sp.config(text=f"{state['sp']:02X}")


        # Vérification du changement de valeur de SP
        if previous_sp is not None:
            print(f"SP actuel : {state['sp']}")
            # Si SP se décrémente
            if state['sp'] < previous_sp:
                mylist.insert(tk.END, state['sp'])
            # Si SP se réincrémente
            elif state['sp'] > previous_sp:
                if mylist.size() > 0:
                    mylist.delete(tk.END)  # On enlève la dernière ligne

        # Mettre à jour la valeur précédente de SP pour la prochaine itération
        previous_sp = state['sp']
        ram = state['ram']

        for addr in range(0, 256, 8):
            chunk = ram[addr:addr+8]
            hex_values = " ".join(f"{b:02X}" for b in chunk)
            myRamList.insert(tk.END, f"{addr:02X}: {hex_values}")

        if (state["out"] != None):
            myOutList.insert(tk.END, state["out"])

        # relance automatique
        root.after(200, update_gui)

    except StopIteration:
        print("Simulation terminée")

#Frame RAM


# ---------------------------------------------------------
#  LECTURE D'UN FICHIER .bin ET LANCEMENT
# ---------------------------------------------------------
if __name__ == "__main__":
    # Nom du fichier binaire à exécuter
    path =""
    args= sys.argv
    if (len(args) > 1):
        filename = args[1]
        print("filename: " + filename)
        with open(filename, "rb") as f:
            program = f.read()
        sim = e3.Simulator(program)
        sim_iter = sim.run()
        update_gui()
        root.mainloop()
    else:
        print("Needs *.bin as parameter")

