# pylint: disable=attribute-defined-outside-init

__all__ = ["HotkeysExtension"]
from functools import partial
import carb.settings
import omni.ext
import omni.ui as ui
import omni.kit.ui

from .window.hotkeys_window import HotkeysWindow

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


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

    def on_startup(self):
        self._window = None

        ui.Workspace.set_show_window_fn(
            HotkeysExtension.WINDOW_NAME,
            partial(self.show_window, HotkeysExtension.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(HotkeysExtension.MENU_PATH, self.show_window, toggle=True, value=show_startup)

        if show_startup:
            ui.Workspace.show_window(HotkeysExtension.WINDOW_NAME)

    def on_shutdown(self):
        ui.Workspace.set_show_window_fn(HotkeysExtension.WINDOW_NAME, None)
        if self._window:
            self._window.destroy()
            self._window = None

    def show_window(self, menu_path: str, visible: bool):
        if visible:
            self._window = HotkeysWindow(HotkeysExtension.WINDOW_NAME)
            self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
        elif self._window:
            self._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(HotkeysExtension.MENU_PATH, checked)

    def _visiblity_changed_fn(self, visible):
        self._set_menu(visible)
        if self._window and not visible:
            self._window.stop_key_capture()
