# Copyright (c) 2022, 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.ui as ui

from . import UINodeCommon


class OgnReadWindowSize:
    @staticmethod
    def compute(db) -> bool:
        db.outputs.height = 0.0
        db.outputs.width = 0.0

        if db.inputs.isViewport:
            try:
                from omni.kit.viewport.window import get_viewport_window_instances

                vp_wins = [win for win in get_viewport_window_instances(None) if isinstance(win, ui.Window)]
            except ImportError:
                db.log_error("No non-legacy viewports found.")
                return False

        widget_path = db.inputs.widgetPath
        if not widget_path:
            window_name = db.inputs.name
            if not window_name:
                db.log_warning("No window name or widgetPath provided.")
                return True

            if db.inputs.isViewport:
                for window in vp_wins:
                    if window.title == window_name:
                        db.outputs.height = window.height
                        db.outputs.width = window.width
                        return True
                db.log_error(f"No viewport named '{window_name}' found.")
                return False

            for window in ui.Workspace.get_windows():
                if isinstance(window, ui.Window) and window.title == window_name:
                    db.outputs.height = window.height
                    db.outputs.width = window.width
                    return True
            db.log_error(f"No window named '{window_name}' found.")
            return False

        window = UINodeCommon.get_widget_window(widget_path)
        if not window:
            db.log_error(f"No widget found at path '{widget_path}'.")
            return False

        if db.inputs.isViewport and window not in vp_wins:
            db.log_error(f"Widget '{widget_path} is not in a viewport window.")
            return False

        db.outputs.height = window.height
        db.outputs.width = window.width
        return True
