# 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.
#
import carb
import omni.ext
import carb.settings
import omni.kit.app
import asyncio

from .application_setup import ApplicationSetup
from .actions import register_actions, deregister_actions
from .viewport_rendering import enable_viewport_rendering
from .imgui_helper import setup_imgui


class AppSetupExtension(omni.ext.IExt):
    """Create Final Configuration"""

    def on_startup(self, ext_id):
        """ setup the window layout, menu, final configuration of the extensions etc """
        self.__ext_id = omni.ext.get_extension_name(ext_id)

        self._settings = carb.settings.get_settings()
        setup_editor = self._settings.get("/app/kit/editor/setup")
        if not setup_editor:
            return

        self._application_setup = ApplicationSetup()
        self._menu_layout = []

        # this is a work around as some Extensions don't properly setup their default setting in time
        self._application_setup.set_defaults()

        # Force enable Axis, Grid, Outline and Lights
        forceEnable = self._settings.get("/app/kit/editor/forceViewportSettings")
        if forceEnable:
            self._application_setup.force_viewport_settings()

        # setup the application title based on settings and few rules
        self._application_setup.setup_application_title()

        # Keep windows open to make sure Welcome window could be visible at startup
        self._application_setup.load_default_layout(keep_windows_open=True)

        self._application_setup.create_trigger_menu()

        self._application_setup.build_layout_menu()

        self._application_setup.setup_menu_layout()

        self._application_setup.setup_menu_order()

        def on_app_ready(*args, **kwargs):
            self._app_ready_sub = None

            # OM-93646: setup imgui when app ready otherwise there will be crash in Linux
            setup_imgui()

            # Start background loading of renderer if requested
            bg_render_load = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer")
            if not bg_render_load:
                return

            # We delay loading those so we leave time for the welcome window
            # and the first tab to be displayed
            async def __load_renderer(bg_render_load):
                # Get setting whether to show the renderer init progress in Viewport
                show_viewport_ready = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/showViewportReady")
                # Get setting for the number of frames to wait before starting the load
                initial_wait = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/initialWait")
                # When not set it will default to 20
                if initial_wait is None:
                    initial_wait = 20
                if initial_wait:
                    app = omni.kit.app.get_app()
                    for _ in range(initial_wait):
                        await app.next_update_async()

                # await self._application_setup.start_loading_renderer(bg_render_load)
                carb.log_info(f"Loading {bg_render_load} in background")
                show_viewport_ready = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/showViewportReady")
                enable_viewport_rendering(renderer=bg_render_load, show_viewport_ready=show_viewport_ready)

            self.__setup_window_task = asyncio.ensure_future(__load_renderer(bg_render_load))

        self._app_ready_sub = omni.kit.app.get_app().get_startup_event_stream().create_subscription_to_pop_by_type(
            omni.kit.app.EVENT_APP_READY,
            on_app_ready,
            name="omni.app.setup.app_ready.startup"
        )

        """
        # At some points around here we will want to close the splash Images
        splash_interface = None
        try:
            import omni.splash
            splash_interface = omni.splash.acquire_splash_screen_interface()

        except (ImportError, ModuleNotFoundError):
            splash_interface = None

        if splash_interface:
            splash_interface.close_all()
        """

        register_actions(self.__ext_id, self._application_setup)

    def on_shutdown(self):
        deregister_actions(self.__ext_id)
        self._app_ready_sub = None
