import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import configparser
import os
from PIL import Image, ImageTk

from scanner import detectar_packs_halycon, detectar_mapas
from copier import aplicar_configuracion
from lang import LANGUAGES


CONFIG_FILE = "data\config.ini"


class OMSIApp(tk.Tk):
    def __init__(self):
        super().__init__()

        self.config_parser = configparser.ConfigParser()
        self._cargar_config()

        self.lang = self.config_parser.get("GENERAL", "language", fallback="es")
        self.txt = LANGUAGES[self.lang]
        self.omsi_root = self.config_parser.get("GENERAL", "omsi_path", fallback="")

        self.packs = {}

        self._crear_ui()
        self._aplicar_textos()

        if self.omsi_root and os.path.isdir(self.omsi_root):
            self._cargar_omsi(self.omsi_root)

    # =====================================================
    # CONFIG
    # =====================================================
    def _cargar_config(self):
        if not os.path.isfile(CONFIG_FILE):
            self.config_parser["GENERAL"] = {
                "language": "es",
                "omsi_path": ""
            }
            self._guardar_config()
        else:
            self.config_parser.read(CONFIG_FILE, encoding="utf-8")

    def _guardar_config(self):
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            self.config_parser.write(f)

    # =====================================================
    # UI
    # =====================================================
    def _crear_ui(self):
        self.title(self.txt["title"])
        self.geometry("820x540")

        frm = ttk.Frame(self, padding=10)
        frm.pack(fill="both", expand=True)

        # ---------- Cabecera ----------
        header = ttk.Frame(frm)
        header.pack(fill="x", pady=(0, 10))

        # Logo
        if os.path.isfile("data\logo.png"):
            img = Image.open("data\logo.png").resize((250, 40), Image.LANCZOS)
            self.logo_img = ImageTk.PhotoImage(img)
            ttk.Label(header, image=self.logo_img).pack(side="left", padx=(0, 10))

        # Idioma
        lang_frame = ttk.Frame(header)
        lang_frame.pack(side="right")

        ttk.Label(lang_frame, text=self.txt["language"]).pack(side="left", padx=5)

        self.cmb_lang = ttk.Combobox(
            lang_frame,
            state="readonly",
            values=["es", "en", "de", "cs", "pl", "pt", "fr"],
            width=5
        )
        self.cmb_lang.set(self.lang)
        self.cmb_lang.pack(side="left")
        self.cmb_lang.bind("<<ComboboxSelected>>", self.cambiar_idioma)

        # ---------- OMSI ----------
        self.btn_omsi = ttk.Button(frm, command=self.seleccionar_omsi)
        self.btn_omsi.pack(anchor="w")

        self.lbl_omsi = ttk.Label(frm)
        self.lbl_omsi.pack(anchor="w", pady=5)

        # ---------- Pack ----------
        self.lbl_pack = ttk.Label(frm)
        self.lbl_pack.pack(anchor="w")

        self.cmb_pack = ttk.Combobox(frm, state="readonly")
        self.cmb_pack.pack(fill="x")
        self.cmb_pack.bind("<<ComboboxSelected>>", self.actualizar_configs)

        # ---------- Humans ----------
        self.lbl_humans = ttk.Label(frm)
        self.lbl_humans.pack(anchor="w")

        self.cmb_humans = ttk.Combobox(frm, state="readonly")
        self.cmb_humans.pack(fill="x")

        # ---------- Drivers ----------
        self.lbl_drivers = ttk.Label(frm)
        self.lbl_drivers.pack(anchor="w")

        self.cmb_drivers = ttk.Combobox(frm, state="readonly")
        self.cmb_drivers.pack(fill="x")

        # ---------- Mapas ----------
        self.lbl_mapas = ttk.Label(frm)
        self.lbl_mapas.pack(anchor="w")

        self.lst_mapas = tk.Listbox(frm, selectmode="multiple", height=10)
        self.lst_mapas.pack(fill="both", expand=True)

        # ---------- Aplicar ----------
        self.btn_apply = ttk.Button(frm, command=self.aplicar)
        self.btn_apply.pack(pady=10)

    # =====================================================
    # Textos / idiomas
    # =====================================================
    def _aplicar_textos(self):
        self.title(self.txt["title"])
        self.btn_omsi.config(text=self.txt["select_omsi"])
        self.lbl_omsi.config(text=self.omsi_root or self.txt["omsi_not_selected"])
        self.lbl_pack.config(text=self.txt["pack"])
        self.lbl_humans.config(text=self.txt["humans"])
        self.lbl_drivers.config(text=self.txt["drivers"])
        self.lbl_mapas.config(text=self.txt["maps"])
        self.btn_apply.config(text=self.txt["apply"])

    def cambiar_idioma(self, _):
        self.lang = self.cmb_lang.get()
        self.txt = LANGUAGES[self.lang]

        self.config_parser["GENERAL"]["language"] = self.lang
        self._guardar_config()

        self._aplicar_textos()

    # =====================================================
    # Lógica OMSI
    # =====================================================
    def seleccionar_omsi(self):
        ruta = filedialog.askdirectory(title=self.txt["select_omsi"])
        if not ruta:
            return

        self._cargar_omsi(ruta)

        self.config_parser["GENERAL"]["omsi_path"] = ruta
        self._guardar_config()

    def _cargar_omsi(self, ruta):
        self.omsi_root = ruta
        self.lbl_omsi.config(text=ruta)

        self.packs = detectar_packs_halycon(ruta)
        self.cmb_pack["values"] = list(self.packs.keys())
        self.cmb_pack.set("")

        self.cmb_humans.set("")
        self.cmb_drivers.set("")
        self.cmb_humans["values"] = []
        self.cmb_drivers["values"] = []

        self.lst_mapas.delete(0, tk.END)
        for mapa in detectar_mapas(ruta):
            self.lst_mapas.insert(tk.END, mapa)

    def actualizar_configs(self, _):
        pack = self.cmb_pack.get()
        data = self.packs.get(pack, {})

        self.cmb_humans["values"] = list(data.get("humans", {}).keys())
        self.cmb_drivers["values"] = list(data.get("drivers", {}).keys())

        self.cmb_humans.set("")
        self.cmb_drivers.set("")

    def aplicar(self):
        pack = self.cmb_pack.get()
        if not pack:
            messagebox.showerror(self.txt["error"], self.txt["select_pack"])
            return

        mapas = [self.lst_mapas.get(i) for i in self.lst_mapas.curselection()]
        if not mapas:
            messagebox.showerror(self.txt["error"], self.txt["select_map"])
            return

        humans = self.cmb_humans.get()
        drivers = self.cmb_drivers.get()

        humans_path = self.packs[pack]["humans"].get(humans) if humans else None
        drivers_path = self.packs[pack]["drivers"].get(drivers) if drivers else None

        resultados = aplicar_configuracion(
            self.omsi_root,
            mapas,
            humans=humans_path,
            drivers=drivers_path
        )

        ok = sum(1 for r in resultados if r[1])
        messagebox.showinfo(
            self.txt["done"],
            self.txt["done_msg"].format(ok=ok, total=len(resultados))
        )


if __name__ == "__main__":
    OMSIApp().mainloop()
