import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.window.extensions

# pylint: disable=protected-access


class TestRegistries(omni.kit.test.AsyncTestCase):
    async def test_add_remove_registry_UNRELIABLE(self):  # noqa
        manager = omni.kit.app.get_app().get_extension_manager()
        settings = carb.settings.get_settings()

        def get_default():
            return settings.get("/app/extensions/registryPublishDefault")

        def get_providers():
            return {p["name"] for p in manager.get_registry_providers()}

        instance = omni.kit.window.extensions.get_instance()()
        instance.show_window(True)
        instance._window._show_properties()
        await omni.kit.app.get_app().next_update_async()

        def get_model():
            widget = instance._window._exts_properties._registries_widget
            return widget._model

        model = get_model()
        model.set_default(model._children[0], True)

        providers_before = get_providers()
        default_before = get_default()
        self.assertEqual(model._children[0].name_model.as_string, default_before)

        # Add new registry using model
        model.add_empty()
        last = model._children[-1]
        last.url_model.as_string = "omniverse://kit-extensions.ov.nvidia.com/exts/kit/debug"
        # name is set automatically
        model.save()
        model = None

        # Wait to propagate and check
        await omni.kit.app.get_app().next_update_async()
        await omni.kit.app.get_app().next_update_async()
        self.assertEqual(get_providers() - providers_before, {"kit/debug"})

        # Make it default now
        get_model().set_default(get_model()._children[-1], True)
        await omni.kit.app.get_app().next_update_async()
        self.assertEqual(get_default(), "kit/debug")

        # Remove!
        get_model().remove_item(get_model()._children[-1])
        await omni.kit.app.get_app().next_update_async()
        await omni.kit.app.get_app().next_update_async()
        self.assertEqual(get_providers(), providers_before)

        # get back default:
        get_model()._children[0].default_model.as_bool = True
        await omni.kit.app.get_app().next_update_async()
        self.assertEqual(get_default(), default_before)
