import webbrowser

import carb.settings
import carb.tokens
import omni.client
import omni.ext
import omni.ui as ui
from omni.kit.documentation.builder import DocumentationBuilderMd, DocumentationBuilderPage
from omni.kit.documentation.builder import get_style as get_doc_style
from omni.kit.welcome.window import register_page
from omni.ui import constant as fl

from .style import ICON_PATH, LEARN_PAGE_STYLE

_extension_instance = None


class LearnPageExtension(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)

        self.__settings = carb.settings.get_settings()
        url = self.__settings.get(f"/exts/{self.__ext_name}/url")
        self._url = carb.tokens.get_tokens_interface().resolve(url)

    def on_shutdown(self):
        global _extension_instance
        _extension_instance = None

    def build_ui(self) -> None:
        with ui.ZStack(style=LEARN_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="VIEW ON THE WEB",
                            image_url=f"{ICON_PATH}/external_link.svg",
                            width=0, spacing=10,
                            clicked_fn=self.__view_on_web,
                            style_type_name_override="Title.Button"
                        )
                        ui.Spacer()
                    ui.Spacer()

                with ui.HStack():
                    ui.Spacer(width=fl._find("welcome_content_padding_x"))
                    with ui.ZStack(style=get_doc_style()):
                        ui.Rectangle(style_type_name_override="Doc.Background")
                        DocumentationBuilderPage(DocumentationBuilderMd(self._url))
                    ui.Spacer(width=fl._find("welcome_content_padding_x"))

                ui.Spacer(height=fl._find("welcome_content_padding_y"))

    def __view_on_web(self):
        web_url = self.__settings.get(f"/exts/{self.__ext_name}/web_url")
        if not web_url:
            web_url = self._url
        webbrowser.open(web_url)
