import { parseInteractiveEngineCommand, serializeInteractiveEngineMessage, } from "./protocol.js";
/** Child-side owner for host-native input forms. */
export class EngineInputFormService {
    constructor(write) {
        this.active = new Map();
        this.nextId = 0;
        this.write = write;
    }
    open(request) {
        const componentId = `input_form_${++this.nextId}`;
        let resolveResult;
        const result = new Promise((resolve) => { resolveResult = resolve; });
        const record = {
            settled: false,
            resolve: (values) => {
                if (record.settled)
                    return;
                record.settled = true;
                this.active.delete(componentId);
                resolveResult(values);
            },
        };
        this.active.set(componentId, record);
        this.send({ type: "engine_input_form_open", componentId, title: request.title, fields: request.fields.map((field) => ({ ...field, choices: field.choices ? [...field.choices] : undefined })) });
        return result;
    }
    handleLine(line) {
        const command = parseInteractiveEngineCommand(line);
        if (!command || !command.type.startsWith("engine_input_form_"))
            return false;
        const record = this.active.get(command.componentId);
        if (!record)
            return true;
        if (command.type === "engine_input_form_submit")
            record.resolve(command.values);
        else if (command.type === "engine_input_form_cancel")
            record.resolve(undefined);
        return true;
    }
    dispose() {
        for (const record of this.active.values())
            record.resolve(undefined);
        this.active.clear();
    }
    send(message) {
        this.write(serializeInteractiveEngineMessage(message));
    }
}
//# sourceMappingURL=engine-input-form.js.map