import inspect
import pathlib

import carb
import carb.settings
import carb.tokens

import omni.kit.app
import omni.kit.test

import omni.kit.renderer.cuda_interop_test

class RendererCudaInteropTest(omni.kit.test.AsyncTestCase):
    async def setUp(self):
        self._settings = carb.settings.acquire_settings_interface()
        self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
        self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
        self._renderer_cuda_interop_test = omni.kit.renderer.cuda_interop_test.acquire_renderer_cuda_interop_test_interface()
        self._renderer.startup()
        self._renderer_cuda_interop_test.startup()

    def __test_name(self) -> str:
        return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"

    async def tearDown(self):
        self._renderer_cuda_interop_test.shutdown()
        self._renderer.shutdown()

        self._renderer_cuda_interop_test = None
        self._renderer = None
        self._app_window_factory = None
        self._settings = None


    async def test_1_render_cuda_interop_test(self):
        app_window = self._app_window_factory.create_window_from_settings()
        app_window.startup_with_desc(
            title="Renderer test OS window",
            width=16,
            height=16,
            x=omni.appwindow.POSITION_CENTERED,
            y=omni.appwindow.POSITION_CENTERED,
            decorations=True,
            resize=True,
            always_on_top=False,
            scale_to_monitor=False,
            dpi_scale_override=-1.0
        )
        self._renderer.attach_app_window(app_window)
        self._app_window_factory.set_default_window(app_window)

        TEST_COLOR = (1, 2, 3, 255)
        test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
        self._renderer.set_clear_color(app_window, test_color_unit)

        self._renderer_cuda_interop_test.startup_resources_for_app_window(app_window)
        self._renderer_cuda_interop_test.setup_simple_comparison_for_app_window(app_window, TEST_COLOR[0], TEST_COLOR[1], TEST_COLOR[2], TEST_COLOR[3])

        test_name = self.__test_name()

        for _ in range(3):
            await omni.kit.app.get_app().next_update_async()

        self._renderer_cuda_interop_test.shutdown_resources_for_app_window(app_window)

        self._app_window_factory.set_default_window(None)
        self._renderer.detach_app_window(app_window)
        app_window.shutdown()
        app_window = None
