import { TypeEditor } from "../TypeEditor.js";
import EmptyView from "../../../../src/view/elements/EmptyView.js";

export class ObservedStringEditor extends TypeEditor {
    build(parent, field, registry) {

        const ctrl = new EmptyView({
            tag: 'input'
        });

        ctrl.attr({
            type: 'text'
        });

        const value = field.adapter.read(parent, field.name);

        let lock = false;

        function sync_up() {
            if (lock) {
                return;
            }

            lock = true;

            ctrl.el.value = value.getValue();

            lock = false;
        }

        function sync_down() {
            if (lock) {
                return;
            }

            lock = true;
            const str = ctrl.el.value;

            value.set(str);

            lock = false;
        }

        ctrl.on.linked.add(sync_up);
        ctrl.bindSignal(value.onChanged, sync_up);
        ctrl.el.addEventListener('input', sync_down);


        return ctrl;
    }
}
