import carb
import omni.kit.commands
import omni.kit.undo

from pxr import Sdf, Usd, UsdGeom
from omni.kit.viewport.utility import get_active_viewport_window, get_active_viewport_camera_path


class CarbProfilerScope:  # pragma: no cover
    def __init__(self, id, name):
        self._id = id
        self._name = name

    def __enter__(self):
        carb.profiler.begin(self._id, self._name)

    def __exit__(self, type, value, trace):
        carb.profiler.end(self._id)


def get_viewport_fps():
    viewport_window = get_active_viewport_window()
    if viewport_window:
        viewport_api = viewport_window.viewport_api
        return viewport_api.frame_info.get("fps")

    return 0


def get_viewport_bound_camera_position(stage: Usd.Stage):
    active_camera_path = get_active_viewport_camera_path()
    camera = stage.GetPrimAtPath(active_camera_path)
    if not camera:
        return None

    xformable = UsdGeom.Xformable(camera)
    transform = xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default())

    return transform.ExtractTranslation()


def switch_viewport_bound_camera_to_persp():
    viewport_window = get_active_viewport_window()
    if viewport_window:
        viewport_api = viewport_window.viewport_api
    else:
        viewport_api = None

    if not viewport_api:
        return

    with omni.kit.undo.disabled():
        omni.kit.commands.execute("SetViewportCameraCommand", camera_path="/OmniverseKit_Persp", viewport_api=viewport_api)
