import asyncio
import carb.settings
import omni.kit.app
import omni.ui as ui
from ..preferences_window import PreferenceBuilder


class GlobalPreferences(PreferenceBuilder):
    def __init__(self):
        super().__init__("")

    def build(self):
        async def on_ok_clicked(dialog):
            import sys
            import carb.events
            import omni.kit.app

            dialog.hide()

            def run_process(args):
                import subprocess
                import platform

                kwargs = {"close_fds": False}
                if platform.system().lower() == "windows":
                    kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP
                subprocess.Popen(args, **kwargs)  # pylint: disable=consider-using-with

            def on_event(e: carb.events.IEvent):
                if e.type == omni.kit.app.PRE_SHUTDOWN_EVENT_TYPE:
                    run_process(sys.argv + ["--reset-user"])

            self._shutdown_sub = omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop(on_event, name="preferences re-start", order=0)
            await omni.kit.app.get_app().next_update_async()
            omni.kit.app.get_app().post_quit()

        def reset_clicked():
            from omni.kit.window.popup_dialog import MessageDialog

            if omni.usd.get_context().has_pending_edit():
                dialog = MessageDialog(
                    title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings",
                    width=400,
                    message=f"This application will restart to remove all custom settings and restore the application to the installed state.\n\nYou will be prompted to save any unsaved changes.",
                    ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)),
                    ok_label="Continue",
                    cancel_label="Cancel",
                )
            else:
                dialog = MessageDialog(
                    title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings",
                    width=400,
                    message=f"This application will restart to remove all custom settings and restore the application to the installed state.",
                    ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)),
                    ok_label="Restart",
                    cancel_label="Cancel",
                )
            dialog.show()

        ui.Button("Reset to Default", clicked_fn=reset_clicked, name="global", tooltip="This will reset all settings back to the installed state after the application is restarted")

    def __del__(self):
        super().__del__()
