import { Controller } from "@hotwired/stimulus"

export class PromptController extends Controller {
    static targets = [
        "label",
        "input",
    ];

    connect() {
        this._callback = null;

        window.runtime.EventsOn("prompt-request", (data) => {
            this.prompt(data.label, (res) => {
                window.runtime.EventsEmit("prompt-response", res);
            });
        });
    }

    prompt(label, callback) {
        this._callback = callback;
        this.labelTarget.textContent = label;
        this.inputTarget.value = "";
        this.element.showModal();
        this.inputTarget.focus();
    }

    submit(ev) {
        ev.preventDefault();
        let value = this.inputTarget.value;
        this.element.close();
        if (this._callback) {
            this._callback(value);
            this._callback = null;
        }
    }

    dismiss(ev) {
        ev.preventDefault();
        this._callback = null;
        this.element.close();
    }
}
