# Copyright (c) 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 weakref

from omni.kit.window.content_browser import get_content_window
from .file_widget import FileWidget


class FilePropertyWidgets(omni.ext.IExt):
    def __init__(self):
        self._registered = False
        self._selection_notifiers = []
        self._content_browser_notifier = None
        super().__init__()

    def on_startup(self, ext_id):
        manager = omni.kit.app.get_app().get_extension_manager()
        self._hooks = manager.subscribe_to_extension_enable(
            lambda _: self._add_selection_notifier(),
            lambda _: self._remove_selection_notifier(),
            ext_name="omni.kit.window.content_browser",
            hook_name="file property widget listener",
        )
        self._register_widget()

    def on_shutdown(self):
        self._hooks = None
        for notifier in self._selection_notifiers:
            notifier.destroy()
        self._selection_notifiers.clear()

        if self._registered:
            self._unregister_widget()

    def _add_selection_notifier(self):
        try:
            self._content_browser_notifier = SelectionNotifier()
            self._selection_notifiers.append(self._content_browser_notifier)
        except Exception as e:
            carb.log_info(f"Could not add file selection notifier: {e}")

    def _remove_selection_notifier(self):
        if self._content_browser_notifier:
            self._selection_notifiers.remove(self._content_browser_notifier)
            self._content_browser_notifier.destroy()
            self._content_browser_notifier = None

    def _register_widget(self):
        import omni.kit.window.property as p

        w = p.get_window()
        if w:
            w.register_widget("file", "stat", FileWidget())

            for notifier in self._selection_notifiers:
                notifier.start()
                notifier._notify_property_window([])  # force a refresh
            self._registered = True

    def _unregister_widget(self):
        try:
            import omni.kit.window.property as p

            w = p.get_window()
            if w:
                for notifier in self._selection_notifiers:
                    notifier.stop()
                w.unregister_widget("file", "stat")
                self._registered = False
        except:
            pass

class SelectionNotifier:
    def __init__(self, property_window_context_id=""):
        from omni.kit.window.content_browser import get_content_window
        self._content_browser_ref = weakref.ref(get_content_window(), lambda ref: self.destroy())
        self._property_window_context_id = property_window_context_id

    def start(self):
        content_browser = self._content_browser_ref()
        if content_browser:
            self._sub = content_browser.subscribe_selection_changed(self._on_content_selection_changed)

    def stop(self):
        self._sub = None

    def destroy(self):
        self.stop()

    def _on_content_selection_changed(self, pane: int, selections):
        self._notify_property_window(selections)

    def _notify_property_window(self, selections):
        import omni.kit.window.property as p

        # TODO _property_window_context_id
        w = p.get_window()
        if w:
            w.notify("file", selections)
