/** @internal NOTE: Internal APIs. Subject to change. Use of these APIs in production applications is not supported. */
import { TypedArray } from './bim-format-types';
import { ArrayBufferReader } from './ArrayBufferReader';
import { DeepImmutable } from '@babylonjs/core';

export interface DecodedGeometricFeatures {
    readonly edges: DeepImmutable<TypedArray>;
}

export class BimGeometricFeaturesReader {
    public constructor() {}

    private readEntry(reader: ArrayBufferReader): [string, DecodedGeometricFeatures] {
        const originalOffset = reader.offsetInBytes;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const [version, headerSize] = reader.uint16(2);
        const [dataSize] = reader.uint32(1);
        const meshHash = reader.uint8(16);
        const [numberOfEdges] = reader.uint32(1);
        reader.offsetInBytes = originalOffset + headerSize;
        const edges = reader.typedArray(numberOfEdges);
        reader.offsetInBytes = originalOffset + headerSize + dataSize;

        return [this.base64EncodedMeshHash(meshHash), { edges: edges.array }];
    }

    public decodeGeometricFeatures(data: ArrayBuffer): Map<string, DecodedGeometricFeatures> {
        const reader = new ArrayBufferReader(data);
        const entries = new Map<string, DecodedGeometricFeatures>();
        while (reader.offsetInBytes < data.byteLength) {
            entries.set(...this.readEntry(reader));
        }
        return entries;
    }

    private base64EncodedMeshHash(meshHash: Uint8Array): string {
        return btoa(String.fromCharCode(...meshHash));
    }
}
