import unittest
import pathlib
import carb
import omni.kit.test
from pxr import UsdShade
from omni.ui.tests.test_base import OmniUiTest
from .inspector_query import InspectorQuery

class TestMouseUIHelper(OmniUiTest):
    # Before running each test
    async def setUp(self):
        await super().setUp()
        extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
        self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
        self._inspector_query = InspectorQuery()

    # After running each test
    async def tearDown(self):
        await super().tearDown()

    async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=10):
        max_loops = 0
        while max_loops < wait_frames:
            _, files_loaded, total_files = usd_context.get_stage_loading_status()
            await omni.kit.app.get_app().next_update_async()
            if files_loaded or total_files:
                continue
            max_loops = max_loops + 1

    async def _simulate_mouse(self, data):
        import omni.appwindow
        import omni.ui as ui

        mouse = omni.appwindow.get_default_app_window().get_mouse()
        input_provider = carb.input.acquire_input_provider()

        window_width = ui.Workspace.get_main_window_width()
        window_height = ui.Workspace.get_main_window_height()
        for type, x, y in data:
            input_provider.buffer_mouse_event(mouse, type, (x / window_width, y / window_height), 0, (x, y))
            await self.wait_for_update()

    async def _debug_capture(self, image_name: str):
        from pathlib import Path
        import omni.renderer_capture

        capture_next_frame = omni.renderer_capture.acquire_renderer_capture_interface().capture_next_frame_swapchain(image_name)
        await self.wait_for_update()
        wait_async_capture = omni.renderer_capture.acquire_renderer_capture_interface().wait_async_capture()
        await self.wait_for_update()

