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

export class NumberEditor extends TypeEditor {
    build(parent, field, registry) {
        function read_value() {
            return field.adapter.read(parent, field.name);
        }

        if (field.adapter.writable) {

            const ctrl = new NumberController();

            let lock = false;

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

                lock = true;

                let v = read_value();

                if (Number.isNaN(v)) {
                    v = 0;
                }

                if (typeof v !== "number") {
                    v = v.valueOf();
                }

                ctrl.value.set(v);

                lock = false;
            }

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

                lock = true;

                field.adapter.write(parent, field.name, ctrl.value.getValue());

                lock = false;
            }

            ctrl.on.linked.add(sync_up);
            ctrl.value.onChanged.add(sync_down);


            return ctrl;
        } else {
            return new LabelView(read_value());
        }
    }
}
