import omni.kit.test
from .test_base import KitLaunchTest
from pathlib import Path

import omni


class TestPostQuitHang(KitLaunchTest):
    """Test for https://nvidia-omniverse.atlassian.net/browse/OM-34203"""

    async def test_post_quit_api(self):
        kit_file = "[dependencies]\n"
        kit_file += '"omni.usd" = {}\n'
        kit_file += '"omni.kit.renderer.core" = {}\n'
        kit_file += '"omni.kit.loop-default" = {}\n'
        kit_file += '"omni.kit.mainwindow" = {}\n'
        kit_file += '"omni.kit.uiapp" = {}\n'
        kit_file += '"omni.kit.menu.file" = {}\n'
        kit_file += '"omni.kit.selection" = {}\n'
        kit_file += '"omni.kit.stage_templates" = {}\n'

        kit_file += """
        # Register extension folder from this repo in kit
        [settings.app.exts]
        folders.'++' = ["${app}/../exts" ]

        [settings.app.extensions]
        enabledDeprecated = [
            ]
        """
        script = f"""
import omni.usd
import omni.kit.app
import asyncio
from pxr import Sdf, Usd


async def main():
    usd_context = omni.usd.get_context()
    for i in range(10):
        root_layer = Sdf.Layer.CreateAnonymous("test.usd")
        stage = Usd.Stage.Open(root_layer)
        await usd_context.attach_stage_async(stage)
        stage = usd_context.get_stage()
        if stage:
            prim = stage.DefinePrim("/World")
            stage.SetDefaultPrim(prim)
            prim = stage.GetDefaultPrim()
            prim.CreateAttribute("testing", Sdf.ValueTypeNames.String).Set("test")
            await usd_context.save_stage_async()
        omni.kit.app.get_app().post_quit()

asyncio.ensure_future(main())
        """

        await self._run_kit_with_script(script, args=["--no-window"], kit_file=kit_file)
