"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
function batchGetItemsFetchAll(dynamoRx, params, backoffTimer, throttleTimeSlot) {
    return dynamoRx.batchGetItems(params)
        .pipe(operators_1.mergeMap(response => {
        if (hasUnprocessedKeys(response)) {
            return rxjs_1.of(response.UnprocessedKeys)
                .pipe(operators_1.delay(backoffTimer.next().value * throttleTimeSlot), operators_1.mergeMap((UnprocessedKeys) => {
                const nextParams = Object.assign({}, params, { RequestItems: UnprocessedKeys });
                return batchGetItemsFetchAll(dynamoRx, nextParams, backoffTimer, throttleTimeSlot);
            }), operators_1.map(combineBatchGetResponses(response)));
        }
        return rxjs_1.of(response);
    }));
}
exports.batchGetItemsFetchAll = batchGetItemsFetchAll;
function hasUnprocessedKeys(response) {
    if (!response.UnprocessedKeys) {
        return false;
    }
    return Object.values(response.UnprocessedKeys)
        .some(t => !!t && t.Keys && t.Keys.length > 0);
}
exports.hasUnprocessedKeys = hasUnprocessedKeys;
/**
 * combines a first with a second response. ConsumedCapacity is always from the latter.
 * @param response1
 */
function combineBatchGetResponses(response1) {
    return (response2) => {
        const tableNames = Object.keys(response1.Responses || {});
        Object.keys(response2.Responses || {})
            .filter(tn => !tableNames.includes(tn))
            .forEach(tn => tableNames.push(tn));
        const Responses = tableNames
            .reduce((u, tableName) => (Object.assign({}, u, { [tableName]: [
                ...(response1.Responses && response1.Responses[tableName] || []),
                ...(response2.Responses && response2.Responses[tableName] || []),
            ] })), {});
        return Object.assign({}, response2, { Responses });
    };
}
exports.combineBatchGetResponses = combineBatchGetResponses;
//# sourceMappingURL=batch-get-utils.js.map