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";

/**
 *
 * @param {string[]} props
 * @param {} value
 * @param {Signal} change_signal
 */
export function make_row_editor(props, value, change_signal = value.onChanged) {

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

    const ctrls = [];

    for (let i = 0; i < props.length; i++) {
        const prop_name = props[i];

        const ctrl = new NumberController({
            value: value[prop_name]
        });

        r.addChild(new LabelView(prop_name));
        r.addChild(ctrl);

        ctrls[i] = ctrl;
    }

    let lock = false;

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

        lock = true;

        for (let i = 0; i < props.length; i++) {
            const prop_name = props[i];

            ctrls[i].value.set(value[prop_name]);
        }


        lock = false;
    };

    const sync_down = () => {

        if (lock) {
            return;
        }

        lock = true;

        const params = ctrls.map(c => c.value.getValue());

        value.set.apply(value, params);

        lock = false;
    };

    r.on.linked.add(sync_up);

    r.bindSignal(change_signal, sync_up);

    for (let i = 0; i < props.length; i++) {

        ctrls[i].value.onChanged.add(sync_down);
    }

    return r;
}

/**
 *
 * @param {Vector3} v3
 * @returns {EmptyView}
 */
export function makeV3_editor(v3) {
    return make_row_editor(['x', 'y', 'z'], v3);
}
