import { BinaryClassSerializationAdapter } from "../../ecs/storage/binary/BinaryClassSerializationAdapter.js";
import { GridPosition2Transform } from "./GridPosition2Transform.js";

export class GridPosition2TransformSerializationAdapter extends BinaryClassSerializationAdapter {

    klass = GridPosition2Transform;
    version = 1;


    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {GridPosition2Transform} value
     */
    serialize(buffer, value) {
        const offsetX = value.offset.x;
        const offsetY = value.offset.y;

        let header = 3;
        if (offsetX === 0 && offsetY === 0) {
            header = 0;
        } else if (offsetX === 0) {
            header = 2;
        } else if (offsetY === 0) {
            header = 1;
        } else {
            //both coordinates are present
            header = 3;
        }

        buffer.writeUint8(header);

        if ((header & 1) !== 0) {
            //write X
            buffer.writeFloat32(offsetX);
        }

        if ((header & 2) !== 0) {
            //write Y
            buffer.writeFloat32(offsetY);
        }
    }

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {GridPosition2Transform} value
     */
    deserialize(buffer, value) {
        //read header
        const header = buffer.readUint8();


        let offsetX = 0, offsetY = 0;

        if ((header & 1) !== 0) {
            //write X
            offsetX = buffer.readFloat32();
        }

        if ((header & 2) !== 0) {
            //write Y
            offsetY = buffer.readFloat32();
        }

        value.offset.set(offsetX, offsetY);
    }
}
