import { TypeEditor } from "../TypeEditor.js";
import { NumberController } from "../../../view/ecs/components/common/NumberController.js";

export class ObservedIntegerEditor extends TypeEditor {
    build(parent, field, registry) {
        const instance = field.adapter.read(parent, field.name);
        const ctrl = new NumberController();

        let lock = false;

        function sync_down() {

            if (lock) {
                return;
            }

            lock = true;

            instance.set(ctrl.value.getValue());

            lock = false;
        }

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

            lock = true;

            ctrl.value.set(instance.getValue());

            lock = false;
        }

        ctrl.on.linked.add(sync_up);

        ctrl.value.onChanged.add(sync_down);
        ctrl.bindSignal(instance.onChanged, sync_up);

        return ctrl;
    }
}
