import os
import carb
import omni.ext
from pxr import Sdf, UsdShade
from pathlib import Path
from .style import UI_STYLES


class TaggingPropertyExtension(omni.ext.IExt):
    def __init__(self):
        self._registered = False
        self._icon_path = ""
        super().__init__()

    def on_startup(self, ext_id):
        manager = omni.kit.app.get_app().get_extension_manager()
        extension_path = manager.get_extension_path(ext_id)
        self._icon_path = Path(extension_path).joinpath("data").joinpath("icons")
        self._hooks = manager.subscribe_to_extension_enable(
            on_enable_fn=lambda _: self._register_widget(),
            on_disable_fn=lambda _: self._unregister_widget(),
            ext_name="omni.kit.window.property",
            hook_name="omni.kit.window.property listener",
        )

    def destroy(self):
        if self._registered:
            self._unregister_widget()

    def on_shutdown(self):
        self._hooks = None

        if self._registered:
            self._unregister_widget()

    def _register_widget(self):
        theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
        style = UI_STYLES[theme]
        # update icon paths
        style["check"]["image_url"] = str(self._icon_path.joinpath("check.svg"))
        style["remove"]["image_url"] = str(self._icon_path.joinpath("remove.svg"))
        style["plus"]["image_url"] = str(self._icon_path.joinpath("plus.svg"))

        try:
            import omni.kit.window.property as p
            from .tagging_attributes_widget import TaggingAttributesWidget

            w = p.get_window()
            if w:
                w.register_widget("prim", "tagging", TaggingAttributesWidget(style))
                self._registered = True
        except Exception as exc:
            carb.log_error(f"Error registering tagging widget {exc}")

    def _unregister_widget(self):
        try:
            import omni.kit.window.property as p

            w = p.get_window()
            if w:
                w.unregister_widget("prim", "tagging")
                self._registered = False
        except Exception as e:
            carb.log_warn(f"Unable to unregister 'tagging:/attributes': {e}")
