# 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 omni.kit.widget.imageview as imageview
import omni.ui as ui
from .singleton import singleton


@singleton
class ViewerWindows:
    """This object keeps all the Image Viewper windows"""

    def __init__(self):
        self.__windows = {}

    def open_window(self, filepath: str) -> ui.Window:
        """Open ImageViewer window with the image file opened in it"""
        if filepath in self.__windows:
            window = self.__windows[filepath]
            window.visible = True
        else:
            window = ImageViewer(filepath)
            # When window is closed, remove it from the list
            window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f))
            self.__windows[filepath] = window

        return window

    def close(self, filepath):
        """Close and remove spacific window"""
        del self.__windows[filepath]

    def close_all(self):
        """Close and remove all windows"""
        self.__windows = {}


class ImageViewer(ui.Window):
    """The window with Image Viewer"""

    def __init__(self, filename: str, **kwargs):
        if "width" not in kwargs:
            kwargs["width"] = 640
        if "height" not in kwargs:
            kwargs["height"] = 480

        super().__init__(filename, **kwargs)
        self.frame.set_style({"Window": {"background_color": 0xFF000000, "border_width": 0}})
        self.frame.set_build_fn(self.__build_window)
        self.__filename = filename

    def __build_window(self):
        """Called to build the widgets of the window"""
        # For now it's only one single widget
        imageview.ImageView(self.__filename, smooth_zoom=True, style={"ImageView": {"background_color": 0xFF000000}})

    def destroy(self):
        pass
