from pathlib import Path
import importlib.util
import sys
import tkinter as tk
from tkinter import colorchooser


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

spec = importlib.util.spec_from_file_location("racecore_v37_for_v38", V37_PATH)
v37 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(v37)


class StudioV38(v37.StudioV37):
    """Rustig verticaal schilderpaneel met een eigen duidelijke kleurkiezer."""

    PANEL_WIDTH = 336
    PANEL_HEIGHT = 184

    def __init__(self):
        super().__init__()
        self.title("RaceCore Livery Studio v3.8 - Paint Controls")

    def build_layout(self):
        super().build_layout()
        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.8")

        # De oude horizontale strook blijft verborgen; alle bestaande methoden
        # worden op dit nieuwe paneel aangesloten via dezelfde attributen.
        old_controls = self.brush_controls
        old_controls.place_forget()
        viewer = self.preview_label.master
        panel = tk.Frame(viewer, bg="#11151D", bd=1, relief="solid")
        panel.place(
            x=18, y=58, width=self.PANEL_WIDTH, height=self.PANEL_HEIGHT
        )
        panel.place_forget()
        panel.pack_propagate(False)
        self.brush_controls = panel
        self.brush_status = tk.StringVar(master=self, value="VRIJ SCHILDEREN")

        title = tk.Frame(panel, bg="#11151D")
        title.pack(fill="x", padx=12, pady=(10, 5))
        tk.Label(
            title, textvariable=self.brush_status,
            font=("Segoe UI", 10, "bold"), fg="#F8FAFC", bg="#11151D",
        ).pack(side="left")
        tk.Label(
            title, text="PENSEEL", font=("Segoe UI", 8, "bold"),
            fg="#67E8F9", bg="#11151D",
        ).pack(side="right")

        colour_row = tk.Frame(panel, bg="#11151D")
        colour_row.pack(fill="x", padx=12, pady=(2, 5))
        tk.Label(
            colour_row, text="Kleur", width=7, anchor="w",
            font=("Segoe UI", 8, "bold"), fg="#94A3B8", bg="#11151D",
        ).pack(side="left")
        self.brush_colour_button = tk.Button(
            colour_row, text="", command=self.choose_brush_colour,
            font=("Segoe UI", 9, "bold"), relief="flat", pady=5,
            cursor="hand2",
        )
        self.brush_colour_button.pack(side="left", fill="x", expand=True)

        size_row = tk.Frame(panel, bg="#11151D")
        size_row.pack(fill="x", padx=12, pady=(1, 7))
        tk.Label(
            size_row, text="Dikte", width=7, anchor="w",
            font=("Segoe UI", 8, "bold"), fg="#94A3B8", bg="#11151D",
        ).pack(side="left")
        tk.Scale(
            size_row, from_=10, to=320, orient="horizontal", showvalue=False,
            variable=self.brush_size, command=self.brush_size_changed,
            bg="#11151D", troughcolor="#334155", activebackground="#22D3EE",
            highlightthickness=0, bd=0, sliderrelief="flat", length=180,
        ).pack(side="left", fill="x", expand=True, padx=(0, 7))
        self.brush_size_label = tk.Label(
            size_row, text="90 px", width=6, anchor="e",
            font=("Segoe UI", 8, "bold"), fg="#67E8F9", bg="#11151D",
        )
        self.brush_size_label.pack(side="right")

        actions = tk.Frame(panel, bg="#11151D")
        actions.pack(fill="x", padx=10, pady=(0, 10))
        for column in range(3):
            actions.grid_columnconfigure(column, weight=1, uniform="paint-action")
        self.brush_undo_button = self._paint_action(
            actions, 0, "STREEK TERUG", self.undo_brush_stroke, "#334155"
        )
        self.brush_finish_button = self._paint_action(
            actions, 1, "OPSLAAN", self.finish_brush_paint, "#0F766E"
        )
        self._paint_action(
            actions, 2, "STOP", self.cancel_panel_paint, "#7F1D1D"
        )
        self._update_brush_colour_button()

    @staticmethod
    def _paint_action(parent, column, text, command, colour):
        button = tk.Button(
            parent, text=text, command=command, font=("Segoe UI", 8, "bold"),
            fg="#F8FAFC", bg=colour, activeforeground="#FFFFFF",
            activebackground="#475569", relief="flat", padx=5, pady=7,
        )
        button.grid(row=0, column=column, sticky="ew", padx=2)
        return button

    def start_brush_paint(self):
        super().start_brush_paint()
        self.brush_controls.place(
            x=18, y=58, relx=0, rely=0,
            width=self.PANEL_WIDTH, height=self.PANEL_HEIGHT, anchor="nw",
        )
        self.brush_controls.lift()
        self.toolbox_button.configure(text="SCHILDEREN", state="disabled")
        self._update_brush_colour_button()

    def choose_brush_colour(self):
        selected = colorchooser.askcolor(
            self.accent.get(), title="Kies penseelkleur", parent=self
        )[1]
        if selected:
            self.set_brush_colour(selected)

    def set_brush_colour(self, colour):
        value = str(colour or "").upper()
        if len(value) != 7 or not value.startswith("#"):
            return False
        try:
            int(value[1:], 16)
        except ValueError:
            return False
        self.accent.set(value)
        self._update_brush_colour_button()
        if self.panel_paint_mode == "brush":
            self.show_selection_overlay()
        return True

    def _update_brush_colour_button(self):
        if not hasattr(self, "brush_colour_button"):
            return
        colour = self.accent.get().upper()
        try:
            red, green, blue = (
                int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:7], 16)
            )
            bright = red * 299 + green * 587 + blue * 114 > 150000
            foreground = "#08152C" if bright else "#FFFFFF"
        except (ValueError, IndexError):
            colour, foreground = "#FFFFFF", "#08152C"
        self.brush_colour_button.configure(
            text=f"KLEUR KIEZEN   {colour}", bg=colour, fg=foreground,
            activebackground=colour, activeforeground=foreground,
        )

    def _update_brush_controls(self):
        super()._update_brush_controls()
        self._update_brush_colour_button()

    def finish_brush_paint(self):
        super().finish_brush_paint()
        if self.panel_paint_mode != "brush":
            self.toolbox_button.configure(text="+ TOEVOEGEN", state="normal")

    def cancel_panel_paint(self, refresh=True):
        was_brush = self.panel_paint_mode == "brush"
        super().cancel_panel_paint(refresh=refresh)
        if was_brush and hasattr(self, "toolbox_button"):
            self.toolbox_button.configure(text="+ TOEVOEGEN", state="normal")


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