"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
const operators_1 = require("rxjs/operators");
const mapper_1 = require("../../../mapper/mapper");
const and_function_1 = require("../../expression/logical-operator/and.function");
const param_util_1 = require("../../expression/param-util");
const request_expression_builder_1 = require("../../expression/request-expression-builder");
const base_request_1 = require("../base.request");
class UpdateRequest extends base_request_1.BaseRequest {
    constructor(dynamoRx, modelClazz, tableName, partitionKey, sortKey) {
        super(dynamoRx, modelClazz, tableName);
        const hasSortKey = this.metaData.getSortKey() !== null;
        if (hasSortKey && (sortKey === null || sortKey === undefined)) {
            throw new Error(`please provide the sort key for attribute ${this.metaData.getSortKey()}`);
        }
        const keyAttributeMap = {};
        // partition key
        const partitionKeyValue = mapper_1.Mapper.toDbOne(partitionKey, this.metaData.forProperty(this.metaData.getPartitionKey()));
        if (partitionKeyValue === null) {
            throw new Error('please provide an acutal value for partition key, got null');
        }
        keyAttributeMap[this.metaData.getPartitionKey()] = partitionKeyValue;
        // sort key
        if (hasSortKey) {
            const sortKeyValue = mapper_1.Mapper.toDbOne(sortKey, this.metaData.forProperty(this.metaData.getSortKey()));
            if (sortKeyValue === null) {
                throw new Error('please provide an actual value for sort key, got null');
            }
            keyAttributeMap[this.metaData.getSortKey()] = sortKeyValue;
        }
        this.params.Key = keyAttributeMap;
    }
    whereAttribute(attributePath) {
        return request_expression_builder_1.RequestExpressionBuilder.addCondition('ConditionExpression', attributePath, this, this.metaData);
    }
    where(...conditionDefFns) {
        const condition = and_function_1.and(...conditionDefFns)(undefined, this.metaData);
        param_util_1.ParamUtil.addExpression('ConditionExpression', condition, this.params);
        return this;
    }
    operations(...updateDefFns) {
        if (updateDefFns && updateDefFns.length) {
            const sortedByActionKeyWord = updateDefFns
                .map(updateDefFn => {
                return updateDefFn(this.params.ExpressionAttributeValues, this.metaData);
            })
                .reduce((result, expr) => {
                if (!result[expr.type]) {
                    result[expr.type] = [];
                }
                result[expr.type].push(expr);
                return result;
            }, {});
            const actionStatements = [];
            let attributeValues = {};
            let attributeNames = {};
            lodash_1.forEach(sortedByActionKeyWord, (value, key) => {
                const statements = [];
                if (value && value.length) {
                    value.forEach(updateExpression => {
                        statements.push(updateExpression.statement);
                        attributeValues = Object.assign({}, attributeValues, updateExpression.attributeValues);
                        attributeNames = Object.assign({}, attributeNames, updateExpression.attributeNames);
                    });
                    actionStatements.push(`${key} ${statements.join(', ')}`);
                }
            });
            const expression = {
                statement: actionStatements.join(' '),
                attributeValues,
                attributeNames,
            };
            param_util_1.ParamUtil.addUpdateExpression(expression, this.params);
            return this;
        }
        else {
            throw new Error('at least one update operation must be defined');
        }
    }
    returnConsumedCapacity(level) {
        this.params.ReturnConsumedCapacity = level;
        return this;
    }
    returnItemCollectionMetrics(returnItemCollectionMetrics) {
        this.params.ReturnItemCollectionMetrics = returnItemCollectionMetrics;
        return this;
    }
    /*
     * The ReturnValues parameter is used by several DynamoDB operations; however,
     * DeleteItem does not recognize any values other than NONE or ALL_OLD.
     */
    returnValues(returnValues) {
        this.params.ReturnValues = returnValues;
        return this;
    }
    execFullResponse() {
        return this.dynamoRx.updateItem(this.params);
    }
    exec() {
        return this.dynamoRx.updateItem(this.params).pipe(operators_1.map(response => {
            return;
        }));
    }
}
exports.UpdateRequest = UpdateRequest;
//# sourceMappingURL=update.request.js.map