import carb
import omni.ext
import omni.ui as ui
from omni.kit.welcome.window import register_page
from omni.ui import constant as fl

from .extensions_widget import ExtensionsWidget
from .style import EXTENSIONS_PAGE_STYLE, ICON_PATH

_extension_instance = None


class ExtensionsPageExtension(omni.ext.IExt):
    def on_startup(self, ext_id):
        self.__ext_name = omni.ext.get_extension_name(ext_id)
        register_page(self.__ext_name, self.build_ui)

    def on_shutdown(self):
        global _extension_instance
        _extension_instance = None

    def build_ui(self) -> None:
        with ui.ZStack(style=EXTENSIONS_PAGE_STYLE):
            # Background
            ui.Rectangle(style_type_name_override="Content")
            with ui.VStack():
                with ui.VStack(height=fl._find("welcome_page_title_height")):
                    ui.Spacer()
                    with ui.HStack():
                        ui.Spacer()
                        ui.Button(
                            text="Open Extension Manager",
                            image_url=f"{ICON_PATH}/external_link.svg",
                            width=0,
                            spacing=10,
                            clicked_fn=self.__show_extension_manager,
                            style_type_name_override="Title.Button"
                        )
                        ui.Spacer()
                    ui.Spacer()

                ExtensionsWidget()

    def __show_extension_manager(self):
        try:
            import omni.kit.app
            manager = omni.kit.app.get_app().get_extension_manager()
            manager.set_extension_enabled_immediate("omni.kit.window.extensions", True)
            from omni.kit.window.extensions import get_instance as get_extensions_instance
            inst_ref = get_extensions_instance()
            inst_ref().show_window(True)
        except Exception as e:
            carb.log_warn(f"Failed to show extension manager: {e}")
