import time
import os
import gc
import machine

class LibPiDOS:
    def __init__(self, cyd):
        self.cyd = cyd
        self.settings = {
            "brightness": 80,
            "volume": 50,
            "timezone": 2,
            "wallpaper": "/sd/wallpaper.bmp"
        }
        self.load_settings()

    def load_settings(self):
        try:
            with open("/config.sys", "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        if k in self.settings:
                            try:
                                # Convertit en int si possible
                                self.settings[k] = int(v)
                            except:
                                self.settings[k] = v
            # Appliquer la luminosité
            self.cyd.backlight(self.settings["brightness"])
        except:
            pass

    def save_settings(self):
        try:
            with open("/config.sys", "w") as f:
                for k, v in self.settings.items():
                    f.write("{}={}\n".format(k, v))
        except:
            pass

    def get_time(self):
        return self.cyd.get_time_string(self.settings["timezone"])

    def get_mem_info(self):
        gc.collect()
        free = gc.mem_free()
        alloc = gc.mem_alloc()
        return free, alloc, free + alloc

    def draw_status_bar(self, y=0, fg=0xFFFF, bg=0x0000):
        # Fond (un peu plus large pour éviter les scories)
        self.cyd.display.fill_hrect(0, y, 320, 12, bg)
        # Heure
        t_str = self.get_time()
        self.cyd.display.draw_text(260, y + 2, t_str, fg, bg=bg)
        # WiFi
        if self.cyd.wlan.isconnected():
            ip = self.cyd.wlan.ifconfig()[0]
            self.cyd.display.draw_text(5, y + 2, "IP: " + ip, fg, bg=bg)
        else:
            self.cyd.display.draw_text(5, y + 2, "WiFi: Offline", fg, bg=bg)
        # Mem
        free_kb = gc.mem_free() // 1024
        self.cyd.display.draw_text(160, y + 2, "RAM: {}K".format(free_kb), fg, bg=bg)

    @staticmethod
    def show_message(cyd, title, message, color=0xFFFF):
        # Une simple boîte de dialogue centrée
        w, h = 200, 80
        x, y = (320 - w) // 2, (240 - h) // 2
        # Ombre
        cyd.display.fill_hrect(x+4, y+4, w, h, 0x0000)
        # Fond
        cyd.display.fill_hrect(x, y, w, h, 0xC618) # Gris silver
        # Bordures
        cyd.display.fill_hrect(x, y, w, 1, 0xFFFF)
        cyd.display.fill_hrect(x, y, 1, h, 0xFFFF)
        # Titre
        cyd.display.fill_hrect(x+2, y+2, w-4, 15, 0x0010) # Bleu foncé
        cyd.display.draw_text(x+5, y+5, title, 0xFFFF, bg=0x0010)
        # Message
        cyd.display.draw_text(x+10, y+30, message[:22], 0x0000, bg=0xC618)
        if len(message) > 22:
            cyd.display.draw_text(x+10, y+45, message[22:44], 0x0000, bg=0xC618)
        
        # Attendre un clic pour fermer
        time.sleep(1)
        while not cyd.touch.get_touch():
            time.sleep_ms(50)
