import { Checksum } from '@iotize/tap/client/impl';
/**
 * Created by IoTize on 19/04/2018.
 * <p>
 * Glue packet chunk to build the original ble packet
 * @param {number} bufferLength
 * @class
 */
export class BLEPacketBuilder {
    constructor(bufferLength) {
        this.bufferOffset = 0;
        this.dataLength = 0;
        this.data = new Uint8Array(bufferLength);
        this.reset();
    }
    /**
     * Append new chunk of data into the builder
     * @param {Array} dataChunk the data chunk. The first byte must be the position offset of this chunk in the buffer (in bytes)
     */
    append(dataChunk) {
        this.bufferOffset = (dataChunk[0] & 0xff) - 1;
        if (this.bufferOffset + dataChunk.length > this.data.length) {
            throw new Error(`Buffer size exceeded. Maximum size is ${this.data.length} byte(s).`);
        }
        for (let i = 1; i < dataChunk.length; i++) {
            this.data[this.bufferOffset + i] = dataChunk[i];
        }
        this.dataLength += dataChunk.length - 1;
    }
    reset() {
        this.dataLength = 0;
        this.bufferOffset = 0;
    }
    hasAllChunks() {
        return this.bufferOffset === -1;
    }
    isChecksumValid() {
        let computedChecksum = this.getComputedChecksum();
        let expectedChecksum = this.getExpectedChecksum();
        return expectedChecksum === computedChecksum;
    }
    getComputedChecksum() {
        return (Checksum.compute(this.data.subarray(0, this.dataLength - 1)) & 0xff);
    }
    getExpectedChecksum() {
        return this.data[this.dataLength - 1];
    }
    /**
     * @return {Array} the result data without the checksum
     */
    getData() {
        return this.data.slice(0, this.dataLength - 1);
        // let result: number[] = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(this.dataLength - 1);
        // /* arraycopy */((srcPts, srcOff, dstPts, dstOff, size) => { if (srcPts !== dstPts || dstOff >= srcOff + size) { while (--size >= 0) dstPts[dstOff++] = srcPts[srcOff++]; } else { let tmp = srcPts.slice(srcOff, srcOff + size); for (let i = 0; i < size; i++) dstPts[dstOff++] = tmp[i]; } })(this.data, 0, result, 0, result.length);
        // return result;
    }
    /**
     * @return {Array} the buffer (with the checksum)
     */
    getBuffer() {
        return this.data;
    }
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW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