"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const process_engine_contracts_1 = require("@process-engine/process_engine_contracts");
class ExecuteProcessService {
    constructor(flowNodeHandlerFactory, datastoreService, messageBusService) {
        this.flowNodeHandlerFactory = undefined;
        this.datastoreService = undefined;
        this.flowNodeHandlerFactory = flowNodeHandlerFactory;
        this.datastoreService = datastoreService;
        this.messageBusService = messageBusService;
    }
    async start(context, processDefinition, processInstance) {
        await processInstance.initializeProcess();
        const startEvent = await this.getStartEventDef(context, processDefinition);
        const processToken = await this.createProcessToken(context);
        await this.executeFlowNode(startEvent, processToken, context);
        await this.end(processInstance, processToken, context);
    }
    async getStartEventDef(context, processDefinition) {
        const startEventDef = processDefinition.nodeDefCollection.data.find((nodeDef) => {
            return nodeDef.type === process_engine_contracts_1.BpmnType.startEvent;
        });
        return startEventDef;
    }
    async executeFlowNode(flowNode, processToken, context) {
        const flowNodeHandler = this.flowNodeHandlerFactory.create(flowNode.type);
        const nextFlowNodeInfo = await flowNodeHandler.execute(flowNode, processToken, context);
        if (nextFlowNodeInfo.flowNode !== null) {
            await this.executeFlowNode(nextFlowNodeInfo.flowNode, nextFlowNodeInfo.processToken, context);
        }
    }
    async end(processInstance, processToken, context) {
        const processEndMessageData = {
            event: 'end',
            token: processToken.data.current,
        };
        const processEndMessage = this.messageBusService.createDataMessage(processEndMessageData, context);
        this.messageBusService.publish(`/processengine/process/${processInstance.id}`, processEndMessage);
    }
    async createProcessToken(context) {
        const processTokenType = await this.datastoreService.getEntityType('ProcessToken');
        return processTokenType.createEntity(context);
    }
}
exports.ExecuteProcessService = ExecuteProcessService;

//# sourceMappingURL=execute_process_service.js.map
