import { mat4 } from "gl-matrix";
import { AttachmentBinding } from "./AttachmentBinding.js";

const scratch_m4_0 = new Float32Array(16);
const scratch_m4_1 = new Float32Array(16);
const scratch_m4_2 = new Float32Array(16);

export class TransformAttachmentBinding extends AttachmentBinding {

    /**
     * TODO make use of Transform.multiplyTransforms for better readability and performance
     */
    update() {

        this.socket.transform.toMatrix(scratch_m4_0);
        this.parentTransform.toMatrix(scratch_m4_1);
        this.attachment.transform.toMatrix(scratch_m4_2);

        mat4.multiply(
            scratch_m4_0, scratch_m4_1, scratch_m4_0
        );
        mat4.multiply(
            scratch_m4_0, scratch_m4_0, scratch_m4_2
        );

        this.attachedTransform.fromMatrix(scratch_m4_0);
    }

    link() {
        this.parentTransform.position.onChanged.add(this.update, this);
        this.parentTransform.rotation.onChanged.add(this.update, this);
        this.parentTransform.scale.onChanged.add(this.update, this);
    }

    unlink() {
        this.parentTransform.position.onChanged.remove(this.update, this);
        this.parentTransform.rotation.onChanged.remove(this.update, this);
        this.parentTransform.scale.onChanged.remove(this.update, this);
    }
}
