import tkinter as tk
from tkinter import filedialog, messagebox
import os
import sys
from PIL import Image, ImageTk
import tempfile
import importlib
import subprocess

BASE_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))

def creer_icone_R290():
    img = Image.open(os.path.join(BASE_DIR,"images", "Icône R290.png"))
    img = img.resize((264, 264))
    return ImageTk.PhotoImage(img)

def creer_icone_R134a():
    img = Image.open(os.path.join(BASE_DIR,"images", "Icône R134a.png"))
    img = img.resize((264, 264))
    return ImageTk.PhotoImage(img)

def creer_icone_R407C():
    img = Image.open(os.path.join(BASE_DIR,"images","Icône R407C.png"))
    img = img.resize((264, 264))
    return ImageTk.PhotoImage(img)

def creer_icone_quitter():
    img = Image.open(os.path.join(BASE_DIR,"images","Icône quitter le programme.png"))
    img = img.resize((264, 264))
    return ImageTk.PhotoImage(img)

class EcranAccueil:
    def __init__(self, root, callback):
        self.root = root
        self.callback = callback
        self.root.title("Bienvenue")

        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        root.geometry(f"{screen_width}x{screen_height}")
        self.root.configure(bg="#add8e6")

        try:
            image_path = os.path.join(BASE_DIR,"images", "Icône menu.png")
            self.image_accueil = ImageTk.PhotoImage(Image.open(image_path).resize((600, 600)))
        except:
            self.image_accueil = None

        if self.image_accueil:
            label_image = tk.Label(self.root, image=self.image_accueil, bg="#add8e6")
            label_image.pack(pady=10)

        label_texte = tk.Label(self.root, text="Programme de visualisation du diagramme enthalpique à partir de mesures",
                               font=("Arial", 28, "bold"), bg="#add8e6")
        label_texte.pack(pady=20)

        label_info = tk.Label(self.root, text="Appuyez sur une touche ou cliquez pour continuer",
                              font=("Arial", 12), bg="#add8e6")
        label_info.pack(pady=10)

        self.root.bind("<Key>", self.continuer)
        self.root.bind("<Button-1>", self.continuer)

    def continuer(self, event=None):
        for widget in self.root.winfo_children():
            widget.destroy()
        self.root.unbind("<Key>")
        self.root.unbind("<Button-1>")
        self.callback()

class MenuPrincipal:
    def __init__(self, root):
        self.root = root
        self.root.title("Tracer le cycle frigorifique complet - Menu Principal")
        self.root.configure(bg="#add8e6")

        main_frame = tk.Frame(root, bg="#add8e6", padx=20, pady=20)
        main_frame.pack(expand=True, fill=tk.BOTH)

        titre = tk.Label(main_frame, text="Le cycle frigorique",
                         font=("Arial", 18, "bold"), bg="#add8e6")
        titre.pack(pady=(0, 30))

        frame_boutons = tk.Frame(main_frame, bg="#add8e6")
        frame_boutons.pack(pady=10)

        button_style = {"font": ("Arial", 12), "width": 20, "height": 5,
                        "borderwidth": 8, "relief": tk.RAISED, "padx": 10, "pady": 7,
                        "bg": "lightgray", "highlightbackground": "black", "highlightthickness": 2}

        # R290
        try:
            self.icone_r290= ImageTk.PhotoImage(Image.open(os.path.join(BASE_DIR, "Icône R290.png")).resize((64, 64)))
        except:
            self.icone_r290= creer_icone_R290()

        frame_r290= tk.Frame(frame_boutons, bg="#add8e6", padx=10, pady=10)
        frame_r290.pack(side="left", padx=20, pady=20)

        label_img_r290 = tk.Label(frame_r290, image=self.icone_r290, bg="#add8e6")
        label_img_r290.pack()
        btn_icone_r290 = tk.Button(frame_r290, text="Propane (hydrocarbure)",
                                  command=self.lancer_r290, **button_style)
        btn_icone_r290.pack(pady=10)

        # R134a
        try:
            self.icone_r134a = ImageTk.PhotoImage(Image.open(os.path.join(BASE_DIR, "Icône R134a.png")).resize((64, 64)))
        except:
            self.icone_r134a = creer_icone_R134a()

        frame_r134a= tk.Frame(frame_boutons, bg="#add8e6", padx=10, pady=10)
        frame_r134a.pack(side="left", padx=20, pady=20)

        label_img_r134a= tk.Label(frame_r134a, image=self.icone_r134a, bg="#add8e6")
        label_img_r134a.pack()
        btn_icone_r134a= tk.Button(frame_r134a, text="Gaz azéothrope",
                                command=self.lancer_r134a, **button_style)
        btn_icone_r134a.pack(pady=10)

        # R407C
        try:
            self.icone_r407C = ImageTk.PhotoImage(Image.open(os.path.join(BASE_DIR, "Icône R407C.png")).resize((64, 64)))
        except:
            self.icone_r407C = creer_icone_R407C()

        frame_r407C= tk.Frame(frame_boutons, bg="#add8e6", padx=10, pady=10)
        frame_r407C.pack(side="left", padx=20, pady=20)

        label_img_r407C= tk.Label(frame_r407C, image=self.icone_r407C, bg="#add8e6")
        label_img_r407C.pack()
        btn_icone_r407C= tk.Button(frame_r407C, text="Mélange zéothrope",
                                command=self.lancer_r407C, **button_style)
        btn_icone_r407C.pack(pady=10)

        # Quitter
        try:
            self.icone_quitter = ImageTk.PhotoImage(Image.open(os.path.join(BASE_DIR, "Icône quitter le programme.png")).resize((64, 64)))
        except:
            self.icone_quitter = creer_icone_quitter()

        frame_quitter = tk.Frame(frame_boutons, bg="#add8e6", padx=10, pady=10)
        frame_quitter.pack(side="left", padx=20, pady=20)

        label_img_quitter = tk.Label(frame_quitter, image=self.icone_quitter, bg="#add8e6")
        label_img_quitter.pack()
        btn_icone_quitter = tk.Button(frame_quitter, text="Quitter le programme",
                                command=self.root.destroy, **button_style)
        btn_icone_quitter.pack(pady=10)

    def lancer_r407C(self):
        self.root.withdraw()
        try:
            base_dir = os.path.dirname(os.path.abspath(__file__))
            fichier_script = "TD_R407C.py"
            chemin_script = os.path.join(base_dir, fichier_script)
            if not os.path.exists(chemin_script):
                messagebox.showerror("Erreur", f"Le fichier {fichier_script} est introuvable dans le dossier :\n{base_dir}")
                self.root.deiconify()
                return
            subprocess.Popen([sys.executable, chemin_script])
        except Exception as e:
            messagebox.showerror("Erreur", f"Une erreur est survenue :\n{str(e)}")
            self.root.deiconify()

    def lancer_r134a(self):
        self.root.withdraw()
        try:
            base_dir= os.path.dirname(os.path.abspath(__file__))
            fichier_script = "TD_R134a.py"
            chemin_script = os.path.join(base_dir, fichier_script)
            if not os.path.exists(chemin_script):
                messagebox.showerror("Erreur", f"Le fichier {fichier_script} est introuvable dans le dossier :\n{base_dir}")
                self.root.deiconify()
                return
            subprocess.Popen([sys.executable, chemin_script])
        except Exception as e:
            messagebox.showerror("Erreur", f"Une erreur est survenue :\n{str(e)}")
            self.root.deiconify()

    def lancer_r290(self):
        self.root.withdraw()
        try:
            base_dir= os.path.dirname(os.path.abspath(__file__))
            fichier_script = "TD_R290.py"
            chemin_script = os.path.join(base_dir, fichier_script)
            if not os.path.exists(chemin_script):
                messagebox.showerror("Erreur", f"Le fichier {fichier_script} est introuvable dans le dossier :\n{base_dir}")
                self.root.deiconify()
                return
            subprocess.Popen([sys.executable, chemin_script])
        except Exception as e:
            messagebox.showerror("Erreur", f"Une erreur est survenue :\n{str(e)}")
            self.root.deiconify()

def lancer_menu():
    for widget in root1.winfo_children():
        widget.destroy()
    MenuPrincipal(root1)

if __name__ == "__main__":
    root1 = tk.Tk()
    root1.state('zoomed')  # Met la fenêtre en plein écran (maximisé)
    EcranAccueil(root1, lancer_menu)
    root1.mainloop()
