import { map } from 'rxjs/operators';
import { randomExponentialBackoffTimer } from '../../../helper';
import { createLogger } from '../../../logger/logger';
import { createToKeyFn, toDb } from '../../../mapper';
import { batchWriteItemsWriteAll } from '../../batchwrite/batch-write-utils';
import { BATCH_WRITE_DEFAULT_TIME_SLOT, BATCH_WRITE_MAX_REQUEST_ITEM_COUNT } from '../../batchwrite/batch-write.const';
import { BaseRequest } from '../base.request';
export class BatchWriteSingleTableRequest extends BaseRequest {
    constructor(dynamoRx, modelClazz) {
        super(dynamoRx, modelClazz);
        this.toKey = createToKeyFn(this.modelClazz);
        this.createDeleteRequest = (item) => ({ DeleteRequest: { Key: this.toKey(item) } });
        this.createPutRequest = (item) => ({ PutRequest: { Item: toDb(item, this.modelClazz) } });
        this.logger = createLogger('dynamo.request.BatchWriteSingleTableRequest', modelClazz);
        this.params.RequestItems = {
            [this.tableName]: [],
        };
    }
    returnItemCollectionMetrics(value) {
        this.params.ReturnItemCollectionMetrics = value;
    }
    delete(items) {
        if (this.params.RequestItems[this.tableName].length + items.length > BATCH_WRITE_MAX_REQUEST_ITEM_COUNT) {
            throw new Error(`batch write takes at max ${BATCH_WRITE_MAX_REQUEST_ITEM_COUNT} items`);
        }
        this.params.RequestItems[this.tableName].push(...items.map(this.createDeleteRequest));
        return this;
    }
    put(items) {
        if (this.params.RequestItems[this.tableName].length + items.length > BATCH_WRITE_MAX_REQUEST_ITEM_COUNT) {
            throw new Error(`batch write takes at max ${BATCH_WRITE_MAX_REQUEST_ITEM_COUNT} items`);
        }
        this.params.RequestItems[this.tableName].push(...items.map(this.createPutRequest));
        return this;
    }
    /**
     * write all given items
     * @param backoffTimer when unprocessed items are returned the next value of backoffTimer is used to determine how many time slots to wait before doing the next request
     * @param throttleTimeSlot the duration of a time slot in ms
     */
    exec(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_WRITE_DEFAULT_TIME_SLOT) {
        this.logger.debug('starting batchWriteItem');
        return this.write(backoffTimer, throttleTimeSlot).pipe(map(() => {
            return;
        }));
    }
    execFullResponse(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_WRITE_DEFAULT_TIME_SLOT) {
        return this.write(backoffTimer, throttleTimeSlot);
    }
    write(backoffTimer, throttleTimeSlot) {
        return batchWriteItemsWriteAll(this.dynamoRx, Object.assign({}, this.params), backoffTimer(), throttleTimeSlot);
    }
}
//# sourceMappingURL=batch-write-single-table.request.js.map