"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.dispatch = dispatch;
const sequelize_1 = require("sequelize");
const database_1 = require("../exception/database");
const index_1 = require("../exception/index");
const invalidaction_1 = require("../exception/invalidaction");
const parse_encoded_action_1 = require("../parse-encoded-action");
async function dispatch({ type, action, validator, parser, applier, eventHandler }) {
    const parsedSerializedAction = (0, parse_encoded_action_1.parseEncodedAction)(action);
    if (!validator(parsedSerializedAction)) {
        throw new invalidaction_1.EncodedActionSchemaMismatchException({ type, action: parsedSerializedAction });
    }
    const actionType = parsedSerializedAction.type;
    try {
        const parsedAction = parser(parsedSerializedAction);
        try {
            await applier(parsedAction);
        }
        catch (ex) {
            if (ex instanceof sequelize_1.UniqueConstraintError) {
                throw new database_1.ApplyActionDatabaseException({
                    staticMessage: 'database unique constraint violation of the fields ' + Object.keys(ex.fields).join(', ')
                });
            }
            else if (ex instanceof sequelize_1.ForeignKeyConstraintError) {
                throw new database_1.ApplyActionDatabaseException({
                    staticMessage: 'database foreign key violation at the table ' + ex.table + '/' + ex.index
                });
            }
            else
                throw ex;
        }
        eventHandler.countEvent('dispatched action:' + actionType);
    }
    catch (ex) {
        if (ex instanceof index_1.ApplyActionException) {
            throw new index_1.ApplyActionException({
                staticMessage: 'error during dispatching ' + actionType + ': ' + ex.staticMessage,
                dynamicMessage: ex.dynamicMessage ? 'error during dispatching ' + actionType + ': ' + ex.dynamicMessage : undefined
            });
        }
        else
            throw ex;
    }
}
//# sourceMappingURL=helper.js.map