import time
import os
import gc
from cyd import CYD, color565
from libpidos import LibPiDOS

# --- PALETTE WINDOWS 3.1 ---
WIN_BG = color565(0, 128, 128)      # Teal classique
WIN_GRAY = color565(192, 192, 192)  # Gris argent
WIN_BLUE = color565(0, 0, 168)      # Bleu titre
WIN_WHITE = 0xFFFF
WIN_BLACK = 0x0000
WIN_BORDER_LIGHT = 0xFFFF
WIN_BORDER_DARK = color565(128, 128, 128)

class GUI:
    @staticmethod
    def draw_3d_rect(cyd, x, y, w, h, color, pressed=False):
        cyd.fill_hrect(x, y, w, h, color)
        top_left = WIN_BORDER_DARK if pressed else WIN_BORDER_LIGHT
        bot_right = WIN_BORDER_LIGHT if pressed else WIN_BORDER_DARK
        # Bordures
        cyd.fill_hrect(x, y, w, 1, top_left)
        cyd.fill_hrect(x, y, 1, h, top_left)
        cyd.fill_hrect(x, y + h - 1, w, 1, bot_right)
        cyd.fill_hrect(x + w - 1, y, 1, h, bot_right)

    @staticmethod
    def draw_window(cyd, x, y, w, h, title):
        # Corps de la fenêtre
        GUI.draw_3d_rect(cyd, x, y, w, h, WIN_GRAY)
        # Barre de titre
        cyd.fill_hrect(x + 2, y + 2, w - 4, 18, WIN_BLUE)
        cyd.display.draw_text(x + 6, y + 6, title, WIN_WHITE, bg=WIN_BLUE)
        # Bouton fermer (X)
        GUI.draw_3d_rect(cyd, x + w - 18, y + 3, 15, 15, WIN_GRAY)
        cyd.display.draw_text(x + w - 14, y + 7, "X", WIN_BLACK, bg=WIN_GRAY)

    @staticmethod
    def draw_icon(cyd, x, y, label):
        # On dessine un petit rectangle blanc pour l'icône
        GUI.draw_3d_rect(cyd, x + 8, y, 16, 16, WIN_WHITE)
        cyd.display.draw_text(x, y + 20, label[:8], WIN_WHITE, bg=WIN_BG)

class Window:
    def __init__(self, x, y, w, h, title, content_func=None):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.title = title
        self.content_func = content_func
        self.visible = False

    def draw(self, cyd):
        if not self.visible: return
        GUI.draw_window(cyd, self.x, self.y, self.w, self.h, self.title)
        if self.content_func:
            self.content_func(cyd, self.x + 4, self.y + 22, self.w - 8, self.h - 26)

    def is_on_title(self, tx, ty):
        return self.visible and self.x <= tx <= self.x + self.w - 20 and self.y <= ty <= self.y + 20

    def is_on_close(self, tx, ty):
        # On élargit un peu la zone pour le stylet (25x25 pixels)
        return self.visible and self.x + self.w - 25 <= tx <= self.x + self.w and self.y <= ty <= self.y + 25

    def is_inside(self, tx, ty):
        return self.visible and self.x <= tx <= self.x + self.w and self.y <= ty <= self.y + self.h

def run_win():
    global cyd
    if 'cyd' not in globals():
        from cyd import CYD
        cyd = CYD()
    
    lib = LibPiDOS(cyd)
    windows = []
    
    def draw_desktop():
        # On force d'abord le nettoyage de l'écran avec la couleur de fond
        cyd.clear(WIN_BG)
        # Puis on tente de mettre l'image par dessus (silencieux si absent)
        wp = lib.settings.get("wallpaper", "/sd/wallpaper.bmp")
        cyd.draw_bmp(wp, 0, 0)
        
        # Barre de tâches
        GUI.draw_3d_rect(cyd, 0, 220, 320, 20, WIN_GRAY)
        cyd.display.draw_text(5, 226, "Demarrer", WIN_BLACK, bg=WIN_GRAY)
        lib.draw_status_bar(y=221, fg=WIN_BLACK, bg=WIN_GRAY)
        
        # Icônes
        GUI.draw_icon(cyd, 20, 20, "Poste")
        GUI.draw_icon(cyd, 20, 70, "DOS")
        GUI.draw_icon(cyd, 20, 120, "TaskMan")
        GUI.draw_icon(cyd, 70, 20, "Clock")
        GUI.draw_icon(cyd, 70, 70, "Setup")
        GUI.draw_icon(cyd, 70, 120, "Info")
        
        for w in windows:
            w.draw(cyd)

    def content_info(cyd, x, y, w, h):
        import gc
        cyd.display.draw_text(x + 10, y + 10, "Win-Pi v1.0", WIN_BLACK, bg=WIN_GRAY)
        cyd.display.draw_text(x + 10, y + 30, "CPU: ESP32", WIN_BLACK, bg=WIN_GRAY)
        cyd.display.draw_text(x + 10, y + 50, "RAM: " + str(gc.mem_free()//1024) + " KB", WIN_BLACK, bg=WIN_GRAY)

    def content_files(cyd, x, y, w, h):
        files = os.listdir("/")
        cyd.display.draw_text(x + 5, y + 5, "Fichiers C:\\", WIN_BLUE, bg=WIN_GRAY)
        for i, f in enumerate(files[:6]):
            cyd.display.draw_text(x + 5, y + 25 + i*15, "- " + f[:15], WIN_BLACK, bg=WIN_GRAY)

    def content_taskman(cyd, x, y, w, h):
        free, alloc, total = lib.get_mem_info()
        cyd.display.draw_text(x + 5, y + 5, "Memoire RAM", WIN_BLUE, bg=WIN_GRAY)
        cyd.display.draw_text(x + 5, y + 25, "Libre: {}K".format(free//1024), WIN_BLACK, bg=WIN_GRAY)
        cyd.display.draw_text(x + 5, y + 40, "Alloc: {}K".format(alloc//1024), WIN_BLACK, bg=WIN_GRAY)
        cyd.display.draw_text(x + 5, y + 55, "Total: {}K".format(total//1024), WIN_BLACK, bg=WIN_GRAY)

    def content_setup(cyd, x, y, w, h):
        cyd.display.draw_text(x + 5, y + 5, "Parametres", WIN_BLUE, bg=WIN_GRAY)
        cyd.display.draw_text(x + 5, y + 25, "Luminosite: {}%".format(lib.settings["brightness"]), WIN_BLACK, bg=WIN_GRAY)
        # Boutons + et -
        GUI.draw_3d_rect(cyd, x + 5, y + 45, 30, 20, WIN_GRAY)
        cyd.display.draw_text(x + 15, y + 50, "-", WIN_BLACK, bg=WIN_GRAY)
        GUI.draw_3d_rect(cyd, x + 40, y + 45, 30, 20, WIN_GRAY)
        cyd.display.draw_text(x + 50, y + 50, "+", WIN_BLACK, bg=WIN_GRAY)

    def content_clock(cyd, x, y, w, h):
        cyd.display.draw_text(x + 10, y + 20, lib.get_time(), WIN_BLUE, bg=WIN_GRAY, size=2)

    win_info = Window(120, 40, 160, 100, "System Info", content_info)
    win_files = Window(40, 40, 180, 140, "Explorateur", content_files)
    win_task = Window(140, 60, 150, 100, "Task Manager", content_taskman)
    win_setup = Window(60, 80, 150, 100, "Setup", content_setup)
    win_clock = Window(80, 40, 160, 80, "Horloge", content_clock)
    
    windows.append(win_info)
    windows.append(win_files)
    windows.append(win_task)
    windows.append(win_setup)
    windows.append(win_clock)

    draw_desktop()
    
    last_touch = None
    last_touch_time = 0
    drag_win = None
    drag_offset = (0, 0)

    try:
        while True:
            touch = cyd.touch.get_touch()
            
            if touch:
                tx, ty = touch
                now = time.ticks_ms()
                
                if not last_touch:
                    is_double = (now - last_touch_time) < 500
                    last_touch_time = now
                    
                    # Check "Démarrer"
                    if 0 <= tx <= 80 and 220 <= ty <= 240:
                        cyd.clear(0)
                        return

                    # Check icônes
                    if 20 <= tx <= 50:
                        if 20 <= ty <= 60: # Poste
                            win_files.visible = True
                            windows.remove(win_files)
                            windows.append(win_files)
                            draw_desktop()
                        elif 70 <= ty <= 110: # DOS (Quitter)
                            if is_double:
                                cyd.clear(0)
                                return
                        elif 120 <= ty <= 160: # TaskMan
                            win_task.visible = True
                            windows.remove(win_task)
                            windows.append(win_task)
                            draw_desktop()
                    elif 70 <= tx <= 100:
                        if 20 <= ty <= 60: # Clock
                            win_clock.visible = True
                            windows.remove(win_clock)
                            windows.append(win_clock)
                            draw_desktop()
                        elif 70 <= ty <= 110: # Setup
                            win_setup.visible = True
                            windows.remove(win_setup)
                            windows.append(win_setup)
                            draw_desktop()
                        elif 120 <= ty <= 160: # Info
                            win_info.visible = True
                            windows.remove(win_info)
                            windows.append(win_info)
                            draw_desktop()
                    
                    # Check fenêtres
                    hit = False
                    for w in reversed(windows):
                        if w.is_on_close(tx, ty):
                            w.visible = False
                            draw_desktop()
                            hit = True
                            break
                        if w.is_on_title(tx, ty):
                            drag_win = w
                            drag_offset = (tx - w.x, ty - w.y)
                            windows.remove(w)
                            windows.append(w)
                            draw_desktop()
                            hit = True
                            break
                        if w.is_inside(tx, ty):
                            # Mettre au premier plan
                            windows.remove(w)
                            windows.append(w)
                            # Logique spécifique Setup (+/-)
                            if w == win_setup:
                                if w.x + 5 <= tx <= w.x + 35 and w.y + 45 + 22 <= ty <= w.y + 65 + 22:
                                    lib.settings["brightness"] = max(10, lib.settings["brightness"] - 10)
                                    cyd.backlight(lib.settings["brightness"])
                                    lib.save_settings()
                                elif w.x + 40 <= tx <= w.x + 70 and w.y + 45 + 22 <= ty <= w.y + 65 + 22:
                                    lib.settings["brightness"] = min(100, lib.settings["brightness"] + 10)
                                    cyd.backlight(lib.settings["brightness"])
                                    lib.save_settings()
                            draw_desktop()
                            hit = True
                            break
                    
                    # Dessiner le curseur temporairement (Supprimé)
                    pass
                
                elif drag_win:
                    nx = tx - drag_offset[0]
                    ny = ty - drag_offset[1]
                    if nx != drag_win.x or ny != drag_win.y:
                        drag_win.x = nx
                        drag_win.y = ny
                        draw_desktop()
                
                last_touch = touch
            else:
                if drag_win:
                    drag_win = None
                    draw_desktop()
                last_touch = None
                
            time.sleep_ms(20)
    except Exception as e:
        if 'console' in globals():
            console.write("Sortie Win-Pi.\n")

# Lancement automatique pour Pi-DOS
run_win()
