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

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

        /**
         * @type {NumericInterval}
         */
        const interval = field.adapter?.read(parent, field.name);

        const r = new EmptyView({
            classList: ["inline-field-row-editor"]
        });

        const c_0 = new NumberController({ value: interval.min });
        const c_1 = new NumberController({ value: interval.max });


        r.addChild(new LabelView("min"))
        r.addChild(c_0);
        r.addChild(new LabelView("max"))
        r.addChild(c_1);

        let lock = false;

        const sync_up = () => {
            if (lock) {
                return;
            }

            lock = true;

            c_0.value.set(interval.min);
            c_1.value.set(interval.max);

            lock = false;
        };

        const sync_down = () => {

            if (lock) {
                return;
            }

            lock = true;

            const v0 = c_0.value.getValue();
            const v1 = c_1.value.getValue();

            if (v0 <= v1) {

                interval.set(
                    v0,
                    v1,
                );
            }

            lock = false;
        };

        r.on.linked.add(sync_up);

        r.bindSignal(interval.onChanged, sync_up);

        r.bindSignal(c_0.value.onChanged, sync_down);
        r.bindSignal(c_1.value.onChanged, sync_down);


        const validate = () => {
            // validation

            if (c_0.value.getValue() > c_1.value.getValue()) {
                // restore
                sync_up();
            }
        };

        c_0.el.addEventListener('blur', validate);
        c_1.el.addEventListener('blur', validate);

        return r;
    }
}
