# 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.
#
__all__ = ["get_window", "PropertyExtension"]
import omni.ext
import omni.kit.ui
import weakref
import omni.ui as ui
from functools import partial
from pathlib import Path
from .window import PropertyWindow
from .templates.header_context_menu import GroupHeaderContextMenu

_property_window_instance = None
TEST_DATA_PATH = ""


def get_window():
    return _property_window_instance if not _property_window_instance else _property_window_instance()


class PropertyExtension(omni.ext.IExt):
    WINDOW_NAME = "Property"
    MENU_PATH = f"Window/{WINDOW_NAME}"

    def __init__(self):
        super().__init__()
        self._window = None
        self._header_context_menu = GroupHeaderContextMenu()

    def on_startup(self, ext_id):
        ui.Workspace.set_show_window_fn(PropertyExtension.WINDOW_NAME, partial(self.show_window, None))

        editor_menu = omni.kit.ui.get_editor_menu()
        if editor_menu:
            self._menu = editor_menu.add_item(PropertyExtension.MENU_PATH, self.show_window, toggle=True, value=True)

        ui.Workspace.show_window(PropertyExtension.WINDOW_NAME)

        manager = omni.kit.app.get_app().get_extension_manager()
        extension_path = manager.get_extension_path(ext_id)
        global TEST_DATA_PATH
        TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")

    def on_shutdown(self):
        self._menu = None

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

        if self._header_context_menu:
            self._header_context_menu.destroy()
            self._header_context_menu = None

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

    def _visiblity_changed_fn(self, visible):
        omni.kit.ui.get_editor_menu().set_value(PropertyExtension.MENU_PATH, visible)

    def show_window(self, menu, value):
        global _property_window_instance

        if value:
            if self._window is None:
                self._window = PropertyWindow()
                self._window.set_visibility_changed_listener(self._visiblity_changed_fn)
                _property_window_instance = weakref.ref(self._window)
            self._window.set_visible(value)

        elif self._window:
            self._window.set_visible(value)
