"""
Standard file used to manage extension load and unload
"""
from pathlib import Path

import carb
import omni.ext
import omni.kit
from omni.kit.window.extensions import ExtsWindowExtension

from .compute_node_widget import ComputeNodeWidget  # noqa: PLE0402
from .menu import Menu  # noqa: PLE0402
from .metaclass import Singleton  # noqa: PLE0402
from .omnigraph_in_extension_window import OmniGraphPage, clear_omnigraph_caches, has_omnigraph_nodes
from .properties_widget import OmniGraphProperties  # noqa: PLE0402


# ==============================================================================================================
class _PublicExtension(omni.ext.IExt):
    """Standard extension support class, necessary for extension management"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__menu = None
        self.__widget = None
        self._properties = None
        self._hook = None

    def register_stage_icon(self):
        """Register the icon used in the stage widget for OmniGraph Prims"""
        try:
            import omni.kit.widget.stage  # noqa: PLW0621
        except ImportError:
            # No stage widget, no need to register icons
            return
        stage_icons = omni.kit.widget.stage.StageIcons()
        current_path = Path(__file__).parent
        icon_path = current_path.parent.parent.parent.parent.joinpath("icons")
        style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
        icon_path = icon_path.joinpath(style)

        for file_name, prim_type in [("OmniGraph.svg", "OmniGraph"), ("OmniGraph.svg", "ComputeGraph")]:
            file_path = icon_path.joinpath(file_name)
            stage_icons.set(prim_type, file_path)

    def on_startup(self):
        """Callback executed when the extension is starting up. Create the menu that houses the UI functionality"""
        self.__menu = Menu()
        self.__widget = ComputeNodeWidget()
        self._properties = OmniGraphProperties()

        manager = omni.kit.app.get_app().get_extension_manager()
        self._hook = manager.subscribe_to_extension_enable(
            on_enable_fn=lambda _: self.register_stage_icon(),
            ext_name="omni.kit.widget.stage",
            hook_name="omni.graph.ui",
        )

        ComputeNodeWidget.get_instance().add_template_path(__file__)
        ExtsWindowExtension.add_tab_to_info_widget(OmniGraphPage)
        ExtsWindowExtension.add_searchable_keyword(
            "@omnigraph",
            "Uses OmniGraph",
            has_omnigraph_nodes,
            clear_omnigraph_caches,
        )

    def on_shutdown(self):
        """Callback executed when the extension is being shut down. The menu will clean up the dangling editors"""
        ExtsWindowExtension.remove_searchable_keyword("@omnigraph")
        ExtsWindowExtension.remove_tab_from_info_widget(OmniGraphPage)

        self.__menu.on_shutdown()
        self.__menu = None
        # Must do this here to avoid the dangling reference
        Singleton.forget(Menu)

        self.__widget.on_shutdown()
        self.__widget = None

        self._properties.on_shutdown()
        self._properties = None
