# 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.
#
from .stageviewer import ViewerWindows
from .stageviewer_utils import is_extension_loaded
from omni.kit.ui import get_custom_glyph_code


def content_available():
    """
    Returns True if the extension "omni.kit.window.content_browser" is loaded.
    """
    return is_extension_loaded("omni.kit.window.content_browser")


class ContentMenu:
    """
    When this object is alive, Content Browser has the additional context menu
    with the items that allow to view usd files.
    """

    def __init__(self):
        self._content_window = None
        self.__view_menu_subscription = None

        if content_available():
            import omni.kit.window.content_browser as content
            self._content_window = content.get_content_window()
            if self._content_window:
                self.__view_menu_subscription = self._content_window.add_context_menu(
                    "Inspect", "show.svg", self._on_show_triggered, self._is_show_visible
                )

    def _is_show_visible(self, content_url):
        '''True if we can show the menu item "View Image"'''
        for ext in ["usd", "usda"]:
            if content_url.endswith(f".{ext}"):
                return True
        return False

    def _on_show_triggered(self, menu, value):
        """Start watching for the layer and run the editor"""
        ViewerWindows().open_window(value)

    def destroy(self):
        """Stop all watchers and remove the menu from the content browser"""
        if self.__view_menu_subscription:
            self._content_window.delete_context_menu(self.__view_menu_subscription)
            self.__view_menu_subscription = None
            self._content_window = None

        ViewerWindows().close_all()
