__all__ = ["ActionsExtension"]
from functools import partial
import carb.settings
import omni.ext
import omni.ui as ui
import omni.kit.ui
from omni.kit.actions.core import get_action_registry

from .window import ActionsWindow

SETTING_SHOW_STARTUP = "/exts/omni.kit.actions.window/showStartup"

class ActionsExtension(omni.ext.IExt):
    WINDOW_NAME = "Actions"
    MENU_PATH = f"Window/{WINDOW_NAME}"

    def on_startup(self):
        self._actions_window = None

        ui.Workspace.set_show_window_fn(
            ActionsExtension.WINDOW_NAME,
            partial(self.show_window, ActionsExtension.MENU_PATH),
        )
        show_startup = carb.settings.get_settings().get(SETTING_SHOW_STARTUP)

        editor_menu = omni.kit.ui.get_editor_menu()
        if editor_menu:
            self._menu = editor_menu.add_item(ActionsExtension.MENU_PATH, self.show_window, toggle=True, value=show_startup)

        if show_startup:
            ui.Workspace.show_window(ActionsExtension.WINDOW_NAME)
        
    def on_shutdown(self):
        if self._actions_window:
            self._actions_window.destroy()
            self._actions_window = None

        ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, None)

    def show_window(self, menu_path: str, visible: bool):
        if visible:
            self._actions_window = ActionsWindow(ActionsExtension.WINDOW_NAME)
            self._actions_window.set_visibility_changed_fn(self._visiblity_changed_fn)
        elif self._actions_window:
            self._actions_window.visible = False

    def _set_menu(self, checked: bool):
        """Set the menu to create this window on and off"""
        editor_menu = omni.kit.ui.get_editor_menu()
        if editor_menu:
            editor_menu.set_value(ActionsExtension.MENU_PATH, checked)

    def _visiblity_changed_fn(self, visible):
        self._set_menu(visible)


