from pathlib import Path
import importlib.util
import sys


APP = Path(__file__).resolve().parent
V31_PATH = APP / "racecore_studio_v31.py"
if str(APP) not in sys.path:
    sys.path.insert(0, str(APP))

spec = importlib.util.spec_from_file_location("racecore_v31_for_v32", V31_PATH)
v31 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(v31)

from core.alignment_tools import alignment_deltas, distribution_deltas


class StudioV32(v31.StudioV31):
    """Visueel uitlijnen en verdelen van een meervoudige selectie."""

    def __init__(self):
        super().__init__()
        self.title("RaceCore Livery Studio v3.2 - Align & Distribute")

    def build_layout(self):
        super().build_layout()
        tk = v31.v30.v29.v28.v27.v26.v25.tk
        header = self.winfo_children()[0]
        for child in header.winfo_children():
            if isinstance(child, tk.Label) and "Livery Studio" in child.cget("text"):
                child.configure(text="Livery Studio  v3.2")

        viewer = self.preview_label.master
        self.alignment_tools = tk.Frame(viewer, bg="#0B1730")
        self.alignment_tools.place(x=20, y=114)
        self._tool_label("X")
        for label, mode in (("LINKS", "min"), ("MIDDEN", "center"), ("RECHTS", "max")):
            self._tool_button(label, lambda value=mode: self.align_selection("x", value))
        self._tool_button("VERDEEL X", lambda: self.distribute_selection("x"), accent=True)
        self._tool_label("Y")
        for label, mode in (("BOVEN", "min"), ("MIDDEN", "center"), ("ONDER", "max")):
            self._tool_button(label, lambda value=mode: self.align_selection("y", value))
        self._tool_button("VERDEEL Y", lambda: self.distribute_selection("y"), accent=True)
        self.update_context_tools()

    def update_multi_count(self):
        super().update_multi_count()
        self.update_context_tools()

    def update_context_tools(self):
        if not hasattr(self, "alignment_tools"):
            return
        if len(self.multi_selection) > 1:
            self.keyboard_hint.place_forget()
            self.multi_tools.place(x=20, y=50)
            self.alignment_tools.place(x=20, y=82)
            self.multi_tools.lift()
            self.alignment_tools.lift()
        else:
            self.multi_tools.place_forget()
            self.alignment_tools.place_forget()
            self.keyboard_hint.place(x=20, y=50)
            self.keyboard_hint.lift()

    def _tool_label(self, text):
        tk = v31.v30.v29.v28.v27.v26.v25.tk
        tk.Label(
            self.alignment_tools, text=text, font=("Segoe UI", 8, "bold"),
            fg="#FDE68A", bg="#0B1730", padx=7, pady=5,
        ).pack(side="left")

    def _tool_button(self, text, command, accent=False):
        tk = v31.v30.v29.v28.v27.v26.v25.tk
        colour = "#0E7490" if accent else "#334155"
        active = "#0891B2" if accent else "#475569"
        tk.Button(
            self.alignment_tools, text=text, command=command,
            font=("Segoe UI", 8, "bold"), fg="#F8FAFC", bg=colour,
            activebackground=active, activeforeground="#F8FAFC",
            relief="flat", padx=7, pady=5,
        ).pack(side="left", padx=(2, 0))

    def editable_alignment_entries(self):
        result = []
        for item, reference, layer, placed in self.selection_assets():
            if layer.get("locked", False):
                continue
            result.append((
                item,
                {
                    "item": item,
                    "kind": reference.kind,
                    "origin": self.drag_origin(reference.kind, layer, item.instance),
                },
                placed.bounds,
            ))
        return result

    def align_selection(self, axis, mode):
        entries = self.editable_alignment_entries()
        deltas = alignment_deltas(
            ((item, bounds) for item, _entry, bounds in entries), axis, mode
        )
        if not deltas:
            self.status.set("Selecteer minimaal twee ontgrendelde objecten")
            return False
        self.apply_individual_deltas(entries, deltas, axis, "Selectie uitgelijnd")
        return True

    def distribute_selection(self, axis):
        entries = self.editable_alignment_entries()
        deltas = distribution_deltas(
            ((item, bounds) for item, _entry, bounds in entries), axis
        )
        if not deltas:
            self.status.set("Selecteer minimaal drie ontgrendelde objecten")
            return False
        label = "Horizontaal gelijk verdeeld" if axis == "x" else "Verticaal gelijk verdeeld"
        self.apply_individual_deltas(entries, deltas, axis, label)
        return True

    def apply_individual_deltas(self, entries, deltas, axis, label):
        moved = False
        for item, entry, _bounds in entries:
            delta = int(round(deltas.get(item, 0)))
            if not delta:
                continue
            dx, dy = (delta, 0) if axis == "x" else (0, delta)
            self.translate_entries([entry], dx, dy)
            moved = True
        if not moved:
            self.status.set("De selectie stond al correct uitgelijnd")
            return
        self.active_snap_guides = {"x": None, "y": None}
        self.record_state()
        self.autosave()
        self.schedule_preview()
        self.refresh_layer_sidebar(self.preview_selected_uid)
        self.show_selection_overlay()
        self.status.set(f"{label} | Undo herstelt de hele groep")

    def show_selection_overlay(self):
        super().show_selection_overlay()
        if hasattr(self, "alignment_tools"):
            self.alignment_tools.lift()


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