import { computeDataTypeByIndex } from "../../binary/type/computeDataTypeByIndex.js";
import { RowFirstTableSpec } from "./RowFirstTableSpec.js";

/**
 *
 * @param {BinaryBuffer} buffer
 * @param {RowFirstTable} table
 */
function deserializeRowFirstTable(buffer, table) {


    //read types
    const numTypes = buffer.readUint16();
    const types = [];
    for (let i = 0; i < numTypes; i++) {
        const typeIndex = buffer.readUint8();

        const type = computeDataTypeByIndex(typeIndex);

        if (type === undefined) {
            throw new Error(`Unknown DataType index ${typeIndex}`);
        }
        types[i] = type;
    }

    //record size
    const bytesPerRecord = buffer.readUint32();

    //read number of records
    const numRecords = buffer.readUint32();

    const numDataBytes = bytesPerRecord * numRecords;
    const data = new Uint8Array(numDataBytes);

    //read data
    buffer.readBytes(data, 0, numDataBytes);

    //update table
    table.spec = RowFirstTableSpec.get(types);
    table.length = numRecords;
    table.capacity = numRecords;
    table.data = data.buffer;
    table.dataView = new DataView(table.data);

}

export { deserializeRowFirstTable };
