var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
define(["require", "exports", "@essential-projects/core_contracts", "@essential-projects/metadata", "./node_instance"], function (require, exports, core_contracts_1, metadata_1, node_instance_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ParallelGatewayEntity extends node_instance_1.NodeInstanceEntity {
        constructor(nodeInstanceEntityDependencyHelper, entityDependencyHelper, context, schema, propertyBag, entityType) {
            super(nodeInstanceEntityDependencyHelper, entityDependencyHelper, context, schema, propertyBag, entityType);
        }
        async initialize() {
            await super.initialize(this);
        }
        get parallelType() {
            return this.getProperty(this, 'parallelType');
        }
        set parallelType(value) {
            this.setProperty(this, 'parallelType', value);
        }
        async execute(context) {
            const nodeDef = await this.nodeDef;
            const processDef = await this.process.processDef;
            const flowsOut = [];
            for (let i = 0; i < processDef.flowDefCollection.data.length; i++) {
                const flowDef = processDef.flowDefCollection.data[i];
                if (flowDef.source.id === nodeDef.id) {
                    flowsOut.push(flowDef);
                }
            }
            const flowsIn = [];
            for (let i = 0; i < processDef.flowDefCollection.data.length; i++) {
                const flowDef = processDef.flowDefCollection.data[i];
                if (flowDef.target.id === nodeDef.id) {
                    flowsIn.push(flowDef);
                }
            }
            if (flowsOut && flowsOut.length > 1 && flowsIn && flowsIn.length === 1) {
                this.parallelType = 'split';
                this.state = 'progress';
                this.changeState(context, 'end', this);
            }
            if (flowsIn && flowsIn.length > 1 && flowsOut && flowsOut.length === 1) {
                this.parallelType = 'join';
                this.state = 'wait';
                if (this.process.processDef.persist) {
                    const internalContext = await this.iamService.createInternalContext('processengine_system');
                    await this.save(internalContext, { reloadAfterSave: false });
                }
            }
        }
        proceed(context, newData, source, applicationId, participant) {
            if (source === undefined) {
                return;
            }
            this._mergeTokenHistory(source.processToken);
            const allPathsArrived = this._checkAllPathsArrived();
            if (!allPathsArrived) {
                return this._persistTokenIfNecessary();
            }
            this.changeState(context, 'end', this);
        }
        _getKeysOfPreviousNodeDefinitions() {
            const allFlowsOfModel = this.process.processDef.flowDefCollection.data;
            const allNodesOfModel = this.process.processDef.nodeDefCollection.data;
            const prevNodeDefinitionKeys = allNodesOfModel
                .filter((nodeDefinition) => {
                const flowFromNodeToGatewayExists = allFlowsOfModel.some((flowDefinition) => {
                    return flowDefinition.source.id === nodeDefinition.id && flowDefinition.target.id === this.nodeDef.id;
                });
                return flowFromNodeToGatewayExists;
            })
                .map((nodeDefinition) => {
                return nodeDefinition.key;
            });
            return prevNodeDefinitionKeys;
        }
        _mergeTokenHistory(tokenWithHistoryToMerge) {
            const gatewayToken = this.processToken;
            if (gatewayToken.data === undefined) {
                gatewayToken.data = {};
            }
            if (gatewayToken.data.history === undefined) {
                gatewayToken.data.history = {};
            }
            gatewayToken.data.history = Object.assign({}, gatewayToken.data.history, tokenWithHistoryToMerge.data.history);
        }
        _checkAllPathsArrived() {
            const prevNodeDefinitionKeys = this._getKeysOfPreviousNodeDefinitions();
            const arrivedPaths = Object.keys(this.processToken.data.history);
            const allPathsArrived = prevNodeDefinitionKeys.every((previousNodeDefinitionKey) => {
                return arrivedPaths.includes(previousNodeDefinitionKey);
            });
            return allPathsArrived;
        }
        async _persistTokenIfNecessary() {
            if (!this.process.processDef.persist) {
                return;
            }
            const internalContext = await this.iamService.createInternalContext('processengine_system');
            const saveOptions = { reloadAfterSave: false };
            return this.processToken.save(internalContext, saveOptions);
        }
    }
    __decorate([
        metadata_1.schemaAttribute({ type: core_contracts_1.SchemaAttributeType.string })
    ], ParallelGatewayEntity.prototype, "parallelType", null);
    exports.ParallelGatewayEntity = ParallelGatewayEntity;
});

//# sourceMappingURL=parallel_gateway.js.map
