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

export class GridPositionSerializationAdapter extends BinaryClassSerializationAdapter {

    klass = GridPosition;
    version = 1;

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {GridPosition} value
     */
    serialize(buffer, value) {
        const x = value.x;
        const y = value.y;

        let header = 0;
        if (Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0) {
            header = 1;
        }

        buffer.writeUint8(header);

        if (header === 1) {
            //both components are uint
            buffer.writeUintVar(x);
            buffer.writeUintVar(y);
        } else {
            buffer.writeFloat32(x);
            buffer.writeFloat32(y);
        }
    }

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

        let x = 0, y = 0;
        if (header === 1) {
            x = buffer.readUintVar();
            y = buffer.readUintVar();
        } else {
            //float
            x = buffer.readFloat32();
            y = buffer.readFloat32();
        }

        value.set(x, y);
    }
}
