# 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 .imageviewer import ViewerWindows
from .imageviewer_utils import is_extension_loaded


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 image files.
    """

    def __init__(self, version: int = 2):
        if version != 2:
            raise RuntimeError("Only version 2 is supported")

        content_window = self._get_content_window()
        if content_window:
            view_menu_name = "Show Image"
            self.__view_menu_subscription = content_window.add_file_open_handler(
                view_menu_name,
                lambda file_path: self._on_show_triggered(view_menu_name, file_path),
                self._is_show_visible,
            )
        else:
            self.__view_menu_subscription = None

    def _get_content_window(self):
        try:
            import omni.kit.window.content_browser as content
        except ImportError:
            return None
        return content.get_content_window()

    def _is_show_visible(self, content_url):
        """True if we can show the menu item View Image"""
        # List of available formats: carb/source/plugins/carb.imaging/Imaging.cpp
        return any(
            content_url.endswith(f".{ext}")
            for ext in ["bmp", "dds", "exr", "gif", "hdr", "jpeg", "jpg", "png", "psd", "svg", "tga"]
        )

    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:
            content_window = self._get_content_window()
            if content_window:
                content_window.delete_file_open_handler(self.__view_menu_subscription)
            self.__view_menu_subscription = None

        ViewerWindows().close_all()
