import { map } from 'rxjs/operators';
import { randomExponentialBackoffTimer } from '../../helper';
import { createToKeyFn, toDb } from '../../mapper';
import { DynamoRx } from '../dynamo-rx';
import { getTableName } from '../get-table-name.function';
import { batchWriteItemsWriteAll } from './batch-write-utils';
import { BATCH_WRITE_DEFAULT_TIME_SLOT, BATCH_WRITE_MAX_REQUEST_ITEM_COUNT } from './batch-write.const';
export class BatchWriteRequest {
    constructor() {
        this.itemCount = 0;
        this.createDeleteRequest = (modelClazz) => {
            const toKey = createToKeyFn(modelClazz);
            return (item) => ({ DeleteRequest: { Key: toKey(item) } });
        };
        this.createPutRequest = (modelClazz) => {
            return (item) => ({ PutRequest: { Item: toDb(item, modelClazz) } });
        };
        this.dynamoRx = new DynamoRx();
        this.params = {
            RequestItems: {},
        };
    }
    returnConsumedCapacity(value) {
        this.params.ReturnConsumedCapacity = value;
        return this;
    }
    returnItemCollectionMetrics(value) {
        this.params.ReturnItemCollectionMetrics = value;
        return this;
    }
    delete(modelClazz, items) {
        this.requestItems(modelClazz, items.map(this.createDeleteRequest(modelClazz)));
        return this;
    }
    put(modelClazz, items) {
        this.requestItems(modelClazz, items.map(this.createPutRequest(modelClazz)));
        return this;
    }
    /**
     *
     * @param backoffTimer generator for how much timeSlots should be waited before requesting next batch. only used when capacity was exceeded. default randomExponentialBackoffTimer
     * @param throttleTimeSlot defines how long one timeSlot is for throttling, default 1 second
     */
    exec(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_WRITE_DEFAULT_TIME_SLOT) {
        return this.write(backoffTimer, throttleTimeSlot).pipe(map(() => {
            return;
        }));
    }
    execFullResponse(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_WRITE_DEFAULT_TIME_SLOT) {
        return this.write(backoffTimer, throttleTimeSlot);
    }
    requestItems(modelClazz, items) {
        if (this.itemCount + items.length > BATCH_WRITE_MAX_REQUEST_ITEM_COUNT) {
            throw new Error(`batch write takes at max ${BATCH_WRITE_MAX_REQUEST_ITEM_COUNT} items`);
        }
        const tableName = getTableName(modelClazz);
        this.params.RequestItems[tableName] = this.params.RequestItems[tableName] || [];
        this.params.RequestItems[tableName].push(...items);
        this.itemCount += items.length;
    }
    write(backoffTimer, throttleTimeSlot) {
        return batchWriteItemsWriteAll(this.dynamoRx, Object.assign({}, this.params), backoffTimer(), throttleTimeSlot);
    }
}
//# sourceMappingURL=batch-write.request.js.map