import { quat_decode_from_uint32 } from "../../../core/geom/3d/quaternion/quat_decode_from_uint32.js";
import { quat_encode_to_uint32 } from "../../../core/geom/3d/quaternion/quat_encode_to_uint32.js";
import { v3_binary_equality_decode } from "../../../core/geom/vec3/serialization/v3_binary_equality_decode.js";
import { v3_binary_equality_encode } from "../../../core/geom/vec3/serialization/v3_binary_equality_encode.js";
import { BinaryClassSerializationAdapter } from "../storage/binary/BinaryClassSerializationAdapter.js";
import { Transform } from "./Transform.js";

export class TransformSerializationAdapter extends BinaryClassSerializationAdapter {

    klass = Transform;
    version = 1;

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {Transform} value
     */
    serialize(buffer, value) {

        const position = value.position;
        const rotation = value.rotation;
        const scale = value.scale;

        buffer.writeFloat64(position.x);
        buffer.writeFloat64(position.y);
        buffer.writeFloat64(position.z);

        const encoded_rotation = quat_encode_to_uint32(
            rotation.x,
            rotation.y,
            rotation.z,
            rotation.w
        );

        buffer.writeUint32(encoded_rotation);

        v3_binary_equality_encode(buffer, scale.x, scale.y, scale.z);
    }

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {Transform} value
     */
    deserialize(buffer, value) {
        const positionX = buffer.readFloat64();
        const positionY = buffer.readFloat64();
        const positionZ = buffer.readFloat64();

        const encoded_rotation = buffer.readUint32();

        v3_binary_equality_decode(buffer, value.scale, 0);

        quat_decode_from_uint32(value.rotation, 0, encoded_rotation);
        value.position.set(positionX, positionY, positionZ);
    }
}
