from pathlib import Path
import importlib.util
import sys


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

spec = importlib.util.spec_from_file_location("racecore_v25_for_v26", V25_PATH)
v25 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(v25)

from core.inline_property_panel import InlinePropertyPanel


class StudioV26(v25.StudioV25):
    """Layer Workspace met blijvende, directe objecteigenschappen."""

    def __init__(self):
        self.inline_commit_job = None
        super().__init__()
        self.title("RaceCore Livery Studio v2.6 - Direct Edit")
        self.geometry("1600x920")
        self.minsize(1320, 780)
        self.refresh_layer_sidebar()

    def build_layout(self):
        super().build_layout()
        header = self.winfo_children()[0]
        for child in header.winfo_children():
            if isinstance(child, v25.tk.Label) and "Livery Studio" in child.cget("text"):
                child.configure(text="Livery Studio  v2.6")

        self.layer_sidebar.configure(width=330)
        tree_box = self.layer_sidebar_tree.master
        tree_box.pack_configure(fill="x", expand=False)
        self.layer_sidebar_tree.configure(height=8)
        self.layer_sidebar_tree.bind(
            "<<TreeviewSelect>>", self._sidebar_selection_changed, add="+"
        )

        self.inline_properties = InlinePropertyPanel(self.layer_sidebar, self)
        self.inline_properties.pack(
            fill="both", expand=True, padx=10, pady=(0, 10)
        )

    def _sidebar_selection_changed(self, _event=None):
        if hasattr(self, "inline_properties"):
            self.inline_properties.load_selected()

    def refresh_layer_sidebar(self, select_uid=None):
        super().refresh_layer_sidebar(select_uid)
        if hasattr(self, "inline_properties"):
            self.inline_properties.load_selected()

    def resolve_layer_uid(self, uid):
        collections = self.reconcile_layer_order()
        for reference in v25.ordered_references(collections, self.layer_order):
            if reference.uid == uid:
                return reference
        return None

    def inline_property_apply(self, uid, key, value, final=False):
        reference = self.resolve_layer_uid(uid)
        if reference is None:
            return
        layer = self.layer_collections()[reference.kind][reference.index]
        if layer.get("locked", False):
            self.status.set("Ontgrendel dit object eerst")
            self.refresh_layer_sidebar(uid)
            return

        if key in {"name", "text"}:
            value = str(value).strip()
            if not value:
                value = "Naamloos object" if key == "name" else " "
        layer[key] = value
        self.schedule_preview()
        self.status.set("Object direct aangepast")

        if key == "name":
            self.refresh_layer_sidebar(uid)
        if final:
            self.flush_inline_commit()
        else:
            self.schedule_inline_commit()

    def schedule_inline_commit(self):
        if self.inline_commit_job is not None:
            try:
                self.after_cancel(self.inline_commit_job)
            except v25.tk.TclError:
                pass
        self.inline_commit_job = self.after(450, self.flush_inline_commit)

    def flush_inline_commit(self):
        if self.inline_commit_job is not None:
            try:
                self.after_cancel(self.inline_commit_job)
            except v25.tk.TclError:
                pass
            self.inline_commit_job = None
        self.record_state()
        self.autosave()

    def apply_state(self, state, record=False):
        if self.inline_commit_job is not None:
            try:
                self.after_cancel(self.inline_commit_job)
            except v25.tk.TclError:
                pass
            self.inline_commit_job = None
        super().apply_state(state, record)

    def destroy(self):
        if self.inline_commit_job is not None:
            try:
                self.after_cancel(self.inline_commit_job)
            except v25.tk.TclError:
                pass
            self.inline_commit_job = None
        super().destroy()


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