"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class FlowNodeHandler {
    async execute(flowNode, processToken, context) {
        const nextFlowNode = await this.executeIntern(flowNode, processToken, context);
        await this.afterExecute(flowNode, processToken, context);
        return nextFlowNode;
    }
    async getNextFlowNodeFor(flowNode, context) {
        const processDefinition = await flowNode.getProcessDef(context);
        const nextFlowNodeId = await this.getNextFlowNodeId(flowNode.id, processDefinition, context);
        return this.getFlowNodeById(nextFlowNodeId, processDefinition);
    }
    getFlowNodeById(flowNodeId, processDefinition) {
        const nextFlowNode = processDefinition.nodeDefCollection.data.find((currentFlowNode) => {
            return currentFlowNode.id === flowNodeId;
        });
        return nextFlowNode;
    }
    async getNextFlowNodeId(flowNodeId, processDefinition, context) {
        const flow = processDefinition.flowDefCollection.data.find((sequenceFlow) => {
            return sequenceFlow.source.id === flowNodeId;
        });
        if (flow === undefined) {
            return null;
        }
        return flow.target.id;
    }
    async afterExecute(flowNode, processToken, context) {
        const tokenData = processToken.data || {};
        const mapper = flowNode.mapper;
        const processDefinition = await flowNode.getProcessDef(context);
        if (mapper !== undefined) {
            const newCurrent = (new Function('token', 'return ' + mapper)).call(tokenData, tokenData);
            tokenData.current = newCurrent;
        }
        tokenData.history = tokenData.history || {};
        if (!tokenData.history[flowNode.key]) {
            tokenData.history[flowNode.key] = tokenData.current;
        }
        else {
            if (!Array.isArray(tokenData.history[flowNode.key])) {
                tokenData.history[flowNode.key] = [tokenData.history[flowNode.key]];
            }
            tokenData.history[flowNode.key].push(tokenData.current);
        }
        processToken.data = tokenData;
        if (processDefinition.persist) {
            await processToken.save(context, { reloadAfterSave: false });
        }
    }
}
exports.FlowNodeHandler = FlowNodeHandler;

//# sourceMappingURL=flow_node_handler.js.map
