import { BiMap } from "../collection/map/BiMap.js";
import { BinaryBuffer } from "./BinaryBuffer.js";

export class EncodingBinaryBuffer extends BinaryBuffer {

    __dictionary = new BiMap();


    writeUTF8String(value) {
        const address = this.__dictionary.getKeyByValue(value);

        if (address === undefined) {
            this.writeUint8(0); //mark as complete value

            const current_address = this.position;

            super.writeUTF8String(value);

            this.__dictionary.add(value, current_address);
        } else {
            //write as reference
            this.writeUint32LE(1 | (address << 1));
        }
    }

    readUTF8String() {
        const header0 = this.readUint8();

        if (header0 === 0) {
            //complete value
            return super.readUTF8String();
        } else {
            this.position--;

            const header = this.readUint32LE();

            const address = header >> 1;

            let value = this.__dictionary.getValueByKey(address);

            if (value === undefined) {
                //remember position
                const p = this.position;

                this.position = address;

                value = super.readUTF8String();

                //restore position
                this.position = p;

                this.__dictionary.add(value, address);
            }

            return value;
        }
    }
}
