import carb
import carb.settings
import omni.client
import omni.kit.app
import omni.kit.ui
import omni.ext
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuItemDescription
from pathlib import Path
from omni import ui
from .about_actions import register_actions, deregister_actions
from .about_window import AboutWindow

WINDOW_NAME = "About"
MENU_NAME = "Help"

_extension_instance = None


class AboutExtension(omni.ext.IExt):
    def on_startup(self, ext_id):
        self._ext_name = omni.ext.get_extension_name(ext_id)

        self._window = AboutWindow()
        self._window.set_visibility_changed_fn(self._on_visibility_changed)

        self._menu_entry = MenuItemDescription(
            name=WINDOW_NAME,
            ticked_fn=self._is_visible,
            onclick_action=(self._ext_name, "toggle_window"),
        )
        omni.kit.menu.utils.add_menu_items([self._menu_entry], name=MENU_NAME)

        ui.Workspace.set_show_window_fn(
            "About",
            lambda value: self._toggle_window(),
        )

        manager = omni.kit.app.get_app().get_extension_manager()
        extension_path = manager.get_extension_path(ext_id)

        global _extension_instance
        _extension_instance = self

        register_actions(self._ext_name, lambda: _extension_instance)

    def on_shutdown(self):
        global _extension_instance
        _extension_instance = None

        self._window.destroy()
        self._window = None

        omni.kit.menu.utils.remove_menu_items([self._menu_entry], name=MENU_NAME)
        self._menu_entry = None
        deregister_actions(self._ext_name)

    def _is_visible(self) -> bool:
        return False if self._window is None else self._window.visible

    def _on_visibility_changed(self, visible):
        self._menu_entry.ticked = visible
        omni.kit.menu.utils.refresh_menu_items(MENU_NAME)

    def toggle_window(self):
        self._window.visible = not self._window.visible

    def show(self, visible: bool):
        self._window.visible = visible

    def menu_show_about(self, plugins):
        version_infos = [
            f"Omniverse Kit {self.kit_version}",
            f"App Name: {self.app_name}",
            f"App Version: {self.app_version}",
            f"Client Library Version: {self.client_library_version}",
            f"USD Resolver Version: {self.usd_resolver_version}",
            f"USD Version: {self.usd_version}",
            f"MDL SDK Version: {self.mdlsdk_version}",
        ]

    @staticmethod
    def _resize_window(window: ui.Window, scrolling_frame: ui.ScrollingFrame):
        scrolling_frame.width = ui.Pixel(window.width - 10)
        scrolling_frame.height = ui.Pixel(window.height - 305)


def get_instance():
    return _extension_instance
