import Vector3 from "../../../../../src/core/geom/Vector3.js";
import { DEG_TO_RAD } from "../../../../../src/core/math/DEG_TO_RAD.js";
import { RAD_TO_DEG } from "../../../../../src/core/math/RAD_TO_DEG.js";
import { TypeEditor } from "../../TypeEditor.js";
import { makeV3_editor } from "../common/makeV3_editor.js";

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

        /**
         * @type {Quaternion}
         */
        const q = field.adapter.read(parent, field.name);

        const euler = new Vector3();

        let lock = false;
        const sync_down = () => {
            if (lock) {
                return;
            }

            lock = true;

            q.fromEulerAnglesXYZ(
                euler.x * DEG_TO_RAD,
                euler.y * DEG_TO_RAD,
                euler.z * DEG_TO_RAD
            );

            lock = false;
        };

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

            lock = true;

            const t = new Vector3();

            q.toEulerAnglesXYZ(t);

            euler.set(
                t.x * RAD_TO_DEG,
                t.y * RAD_TO_DEG,
                t.z * RAD_TO_DEG,
            );

            lock = false;
        }

        const editor = makeV3_editor(euler);

        editor.bindSignal(q.onChanged, sync_up);
        editor.bindSignal(euler.onChanged, sync_down);

        editor.on.linked.add(sync_up);

        return editor;
    }
}
