import { forEach } from 'lodash';
import { map, tap } from 'rxjs/operators';
import { hasSortKey } from '../../../decorator/metadata';
import { createLogger } from '../../../logger/logger';
import { toDbOne } from '../../../mapper';
import { addUpdateExpression } from '../../expression/param-util';
import { WriteRequest } from '../write.request';
export class UpdateRequest extends WriteRequest {
    constructor(dynamoRx, modelClazz, tableName, partitionKey, sortKey) {
        super(dynamoRx, modelClazz, tableName);
        this.logger = createLogger('dynamo.request.UpdateRequest', modelClazz);
        if (hasSortKey(this.metadata) && (sortKey === null || sortKey === undefined)) {
            throw new Error(`please provide the sort key for attribute ${this.metadata.getSortKey()}`);
        }
        const keyAttributeMap = {};
        // partition key
        const partitionKeyValue = 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(this.metadata)) {
            const sortKeyValue = 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;
    }
    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 = {};
            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,
            };
            addUpdateExpression(expression, this.params);
            return this;
        }
        else {
            throw new Error('at least one update operation must be defined');
        }
    }
    execFullResponse() {
        this.logger.debug('request', this.params);
        return this.dynamoRx.updateItem(this.params).pipe(tap(response => this.logger.debug('response', response)));
    }
    exec() {
        return this.execFullResponse().pipe(map(response => {
            return;
        }));
    }
}
//# sourceMappingURL=update.request.js.map