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

export class Sampler2DSerializationAdapter extends BinaryClassSerializationAdapter {

    version = 0;
    klass = Sampler2D;

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

        const width = value.width;
        const height = value.height;

        const itemSize = value.itemSize;

        buffer.writeUint16(width);
        buffer.writeUint16(height);

        buffer.writeUint8(itemSize);

        if (value.data instanceof Uint8Array) {
            //data type
            buffer.writeUint8(0);


            const byteSize = width * height * itemSize;

            buffer.writeBytes(value.data, 0, byteSize);

        } else {
            throw new TypeError(`Unsupported data type`);
        }
    }

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {Sampler2D} value
     */
    deserialize(buffer, value) {
        value.width = buffer.readUint16();
        value.height = buffer.readUint16();

        value.itemSize = buffer.readUint8();

        const dataType = buffer.readUint8();

        if (dataType === 0) {

            const numBytes = value.height * value.width * value.itemSize;
            value.data = new Uint8Array(numBytes);

            buffer.readBytes(value.data, 0, numBytes);

        } else {
            throw new TypeError(`Unsupported data type (${dataType})`);
        }
    }
}
