import omni.ui as ui


class SelectionSetWindow():
    def __init__(self, callback):
        self._callback = callback
        window = ui.Window(
            "Selection Set Name",
            width=300,
            height=110,
            flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_MODAL
            )

        with window.frame:
            def on_create(widget):
                self._callback(widget.model.as_string)
                window.visible = False

            def on_cancel():
                window.visible = False

            with ui.VStack(
                height=0,
                spacing=5,
                name="top_level_stack",
                style={"VStack::top_level_stack": {"margin": 5}, "Button": {"margin": 0}},
            ):
                ui.Label("New selection set name:")
                widget = ui.StringField()
                ui.Spacer(width=5, height=5)
                with ui.HStack(spacing=5):
                    create_button = ui.Button("Create", enabled=False, clicked_fn=lambda w=widget: on_create(w))
                    ui.Button("Cancel", clicked_fn=lambda: on_cancel())

                def window_pressed_key(key_index, key_flags, key_down):
                    import carb.input

                    create_button.enabled = bool(len(widget.model.as_string) > 0)
                    key_mod = key_flags & ~ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD
                    if create_button.enabled and carb.input.KeyboardInput(key_index) in [carb.input.KeyboardInput.ENTER, carb.input.KeyboardInput.NUMPAD_ENTER] and key_mod == 0 and key_down:
                        on_create(widget)

                widget.focus_keyboard()
                window.set_key_pressed_fn(window_pressed_key)

        self._window = window
        self._widget = widget

    def shutdown(self):
        self._callback = None
        del self._window

    def show(self):
        self._window.visible = True
        self._widget.model.set_value("")
        self._widget.focus_keyboard()
