import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.kit.commands
from carb.input import KeyboardInput


class TestMenuEditRename(omni.kit.test.AsyncTestCase):
    async def setUp(self):
        from omni.kit.test_suite.helpers import arrange_windows

        await arrange_windows()
        await omni.usd.get_context().new_stage_async()

    async def tearDown(self):
        pass

    async def test_edit_menu_rename(self):
        import omni.kit.material.library
        from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, get_prims

        # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
        await omni.kit.material.library.get_mdl_list_async()
        await ui_test.human_delay()

        ## create prim
        omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
        await ui_test.human_delay()

        # verify prims were created
        stage = omni.usd.get_context().get_stage()
        prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
        self.assertTrue(prim_list == ['/Sphere'])

        # select prim
        omni.usd.get_context().get_selection().set_selected_prim_paths(['/Sphere'], True)
        await ui_test.human_delay()
    
        # use menu - As omni.kit.window.stage is loaded then that should
        # be used to rename, not dialog like in edit_test_func_edit_rename
        await ui_test.menu_click("Edit/Rename")

        # type new name
        await ui_test.human_delay()
        await ui_test.emulate_keyboard_press(KeyboardInput.DEL)
        await ui_test.human_delay()
        await ui_test.emulate_char_press("MyHovercraftISFullOfEels@@xx1/\!!")
        await ui_test.human_delay()
        await ui_test.emulate_keyboard_press(KeyboardInput.ENTER)
        await ui_test.human_delay()

        # verify rename worked and bad characters were handled
        prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
        self.assertTrue(prim_list == ['/MyHovercraftISFullOfEels__xx1____'])

        # test undo
        omni.kit.undo.undo()
        await ui_test.human_delay()
        prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
        self.assertTrue(prim_list == ['/Sphere'])
