"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const MAX_INDEXING_BYTES = 16 * Math.pow(2, 20);
const MAX_INDEXING_COUNT = 1000;
const COMMA = Buffer.from(',');
const OPEN = Buffer.from('{"value":[');
const CLOSE = Buffer.from(']}');
class IndexBuffer {
    constructor(flushHandler) {
        this.flushHandler = flushHandler;
        this.chunks = [];
        this.bytes = 0;
        this.count = 0;
    }
    add(document) {
        if (!this.count) {
            this.chunk(OPEN);
        }
        const next = Buffer.from(JSON.stringify(document));
        if (next.byteLength > MAX_INDEXING_BYTES) {
            throw new Error(`Document #${this.count} contains ${next.byteLength} bytes, which exceeds maximum of ${MAX_INDEXING_BYTES}`);
        }
        else if (next.byteLength + COMMA.byteLength + CLOSE.byteLength + this.bytes > MAX_INDEXING_BYTES) {
            return this.flush();
        }
        else {
            if (this.count > 0) {
                this.chunk(COMMA);
            }
            this.chunk(next);
            this.count += 1;
        }
        if (this.count >= MAX_INDEXING_COUNT) {
            return this.flush();
        }
        else {
            return Promise.resolve();
        }
    }
    flush() {
        if (this.count) {
            this.chunk(CLOSE);
            const data = Buffer.concat(this.chunks);
            this.reset();
            return this.flushHandler(data);
        }
    }
    chunk(chunk) {
        this.chunks.push(chunk);
        this.bytes += chunk.byteLength;
    }
    reset() {
        this.chunks.length = 0;
        this.bytes = 0;
        this.count = 0;
    }
}
exports.IndexBuffer = IndexBuffer;
//# sourceMappingURL=index-buffer.js.map