import tkinter as tk
from tkinter import messagebox
import time
import os
import subprocess

# --- Fonctions principales ---

def demarrer():
    """Démarre le compte à rebours"""
    global total_seconds, running
    if running:
        return
    try:
        h = int(entree_h.get())
        m = int(entree_m.get())
        s = int(entree_s.get())
        total_seconds = h * 3600 + m * 60 + s
        if not (0 < total_seconds <= 3 * 3600):
            raise ValueError
    except ValueError:
        messagebox.showerror("Erreur", "Veuillez entrer une durée valide (1 s à 3 h).")
        return

    running = True
    btn_pause.config(state="normal", text="⏸ Pause")
    mettre_a_jour()

def mettre_a_jour():
    """Met à jour l'affichage chaque seconde"""
    global total_seconds, running
    if running:
        if total_seconds > 0:
            h = total_seconds // 3600
            m = (total_seconds % 3600) // 60
            s = total_seconds % 60
            label_temps.config(text=f"{h:02d}:{m:02d}:{s:02d}")
            total_seconds -= 1
            root.after(1000, mettre_a_jour)
        else:
            label_temps.config(text="00:00:00", fg="red")
            running = False
            signaler_fin()

def signaler_fin():
    """Joue un bip et envoie une notification système"""
    # Bip terminal
    print("\a")  # (fonctionne souvent dans un terminal)
    try:
        print("\a")
        #os.system('paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null')
    except Exception:
        pass

    # Notification système
    try:
        subprocess.Popen(['notify-send', '⏰ Compte à rebours', 'Temps écoulé !'])
    except FileNotFoundError:
        pass

    messagebox.showinfo("Fin", "⏰ Temps écoulé !")

def pause_ou_reprendre():
    """Met en pause ou reprend le compte à rebours"""
    global running
    if running:
        running = False
        btn_pause.config(text="▶️ Reprendre")
    else:
        running = True
        btn_pause.config(text="⏸ Pause")
        mettre_a_jour()

def reinitialiser():
    """Réinitialise le compteur"""
    global running, total_seconds
    running = False
    total_seconds = 0
    label_temps.config(text="00:00:00", fg="#0078D7")
    btn_pause.config(state="disabled", text="⏸ Pause")

# --- Début du programme ---
# --- Fenêtre principale ---
root = tk.Tk()
root.title("⏳ Compte à rebours")
root.geometry("320x220")
root.resizable(False, False)
print("\a")

# --- Variables ---
running = False
total_seconds = 0

# --- Cadre de saisie ---
cadre = tk.Frame(root)
cadre.pack(pady=10)

tk.Label(cadre, text="Durée (HH:MM:SS)").grid(row=0, column=0, columnspan=5)

entree_h = tk.Entry(cadre, width=3, justify="center")
entree_m = tk.Entry(cadre, width=3, justify="center")
entree_s = tk.Entry(cadre, width=3, justify="center")

entree_h.insert(0, "00")
entree_m.insert(0, "10")
entree_s.insert(0, "00")

entree_h.grid(row=1, column=0, padx=2)
tk.Label(cadre, text=":").grid(row=1, column=1)
entree_m.grid(row=1, column=2, padx=2)
tk.Label(cadre, text=":").grid(row=1, column=3)
entree_s.grid(row=1, column=4, padx=2)

# --- Label d'affichage ---
label_temps = tk.Label(root, text="00:00:00", font=("Consolas", 36, "bold"), fg="#0078D7")
label_temps.pack(pady=10)

# --- Boutons de contrôle ---
cadre_btn = tk.Frame(root)
cadre_btn.pack()

tk.Button(cadre_btn, text="▶️ Démarrer", command=demarrer).grid(row=0, column=0, padx=5)
btn_pause = tk.Button(cadre_btn, text="⏸ Pause", state="disabled", command=pause_ou_reprendre)
btn_pause.grid(row=0, column=1, padx=5)
tk.Button(cadre_btn, text="🔁 Réinitialiser", command=reinitialiser).grid(row=0, column=2, padx=5)

# --- Boucle principale ---
root.mainloop()
