# Copyright (c) 2018-2020, NVIDIA CORPORATION.  All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto.  Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation of the omni.ui aka UI Framework"""

from .scripts.ui_doc import UIDoc
from functools import partial
import asyncio
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.ui as ui

EXTENSION_NAME = "Omni.UI Documentation"


class ExampleExtension(omni.ext.IExt):
    """The Demo extension"""

    WINDOW_NAME = "Omni::UI Doc"
    _ui_doc = None

    def __init__(self):
        super().__init__()

    @staticmethod
    def ui_doc():
        return ExampleExtension._ui_doc

    def get_name(self):
        """Return the name of the extension"""
        return EXTENSION_NAME

    def on_startup(self, ext_id):
        """Caled to load the extension"""
        extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)

        ExampleExtension._ui_doc = UIDoc(extension_path)
        ui.Workspace.set_show_window_fn(
            ExampleExtension.WINDOW_NAME,
            lambda show: show and ExampleExtension._ui_doc.build_window(ExampleExtension.WINDOW_NAME),
        )
        ui.Workspace.show_window(ExampleExtension.WINDOW_NAME)

        # Dock this extension into mainwindow if running as standalone
        settings = carb.settings.get_settings()
        standalone_mode = settings.get_as_bool("app/settings/standalone_mode")
        if standalone_mode:
            asyncio.ensure_future(self._dock_window(ExampleExtension.WINDOW_NAME, omni.ui.DockPosition.SAME))

    def on_shutdown(self):
        """Called when the extesion us unloaded"""
        ExampleExtension._ui_doc.shutdown()
        ExampleExtension._ui_doc = None

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

    async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0):
        frames = 3
        while frames > 0:
            if omni.ui.Workspace.get_window(window_title):
                break
            frames = frames - 1
            await omni.kit.app.get_app().next_update_async()

        window = omni.ui.Workspace.get_window(window_title)
        dockspace = omni.ui.Workspace.get_window("DockSpace")

        if window and dockspace:
            window.dock_in(dockspace, position, ratio=ratio)
            window.dock_tab_bar_visible = False

