export default class BufferReader {


    private buffer: ArrayBuffer;
    private index: number;
    private dataView: DataView;

    constructor(buffer: ArrayBuffer) {

        this.buffer = buffer;
        this.index = 0;
        this.dataView = new DataView(this.buffer);
    }

    seek(position: number) {

        this.index = position;
    }

    getIndex() {

        return this.index;
    }

    getSize() {

        return this.buffer.byteLength;
    }

    skip(length: number) {

        this.index += length;
    }

    readBytes(length: number) {

        return this.dataView.buffer.slice(this.index, this.index += length);

    }

    readInt32() {

        let value = this.dataView.getInt32(this.index, true);
        this.index += 4;
        return value;
    }

    readInt16() {

        let value = this.dataView.getInt16(this.index, true);
        this.index += 2;
        return value;
    }

    readFloat32() {

        let value = this.dataView.getFloat32(this.index, true);
        this.index += 4;
        return value;
    }

    readUint8() {


        let value = this.dataView.getUint8(this.index);
        this.index += 1;
        return value;
    }

    readInt8() {


        let value = this.dataView.getInt8(this.index);
        this.index += 1;
        return value;
    }

    readUint32() {

        let value = this.dataView.getUint32(this.index, true);
        this.index += 4;
        return value;
    }

    readUint16() {

        let value = this.dataView.getUint16(this.index, true);
        this.index += 2;
        return value;
    }

    readChar() {

        if (this.index > this.buffer.byteLength - 1) return "-";
        let value = String.fromCharCode(this.dataView.getUint8(this.index));
        this.index += 1;
        return value;
    }

    readString(length: number) {

        let str = ""
        for (let i = 0; i < length; i++) {
            str += this.readChar()
        }
        return str;
    }

    readZeroTerminatedString() {

        let returnString = "";

        while (true)
        {
            let char = this.readChar();

            if (char == "\0")
            {
                break;
            }

            returnString += char;
        }

        return returnString;

    }

    asString() {

        let str = '';
        for(let i = 0; i < this.buffer.byteLength; i++) {

            str += this.readChar()

        }

        return str
    }
}