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) {
        if (!dataChunk || dataChunk.length < 2) {
            return;
        }
        this.bufferOffset = (dataChunk[0] & 0xff) - 1;
        if (this.bufferOffset + dataChunk.length > this.data.length) {
            throw new Error(// TODO ble 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;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