Sync Integ to Master
[sdc.git] / catalog-ui / src / app / directives / graphs-v2 / composition-graph / utils / match-capability-requierment-utils.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import * as _ from "lodash";
22 import {
23     Requirement, CompositionCiLinkBase, CapabilitiesGroup, RequirementsGroup, Match,
24     CompositionCiNodeBase, Component, Capability
25 } from "app/models";
26 import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
27 /**
28  * Created by obarda on 1/1/2017.
29  */
30
31 export class MatchCapabilitiesRequirementsUtils {
32
33     /**
34      * Shows + icon in corner of each node passed in
35      * @param filteredNodesData
36      * @param cy
37      */
38     public highlightMatchingComponents(filteredNodesData, cy:Cy.Instance) {
39         _.each(filteredNodesData, (data:any) => {
40             let node = cy.getElementById(data.id);
41             cy.emit('showhandle', [node]);
42         });
43     }
44
45     /**
46      * Adds opacity to each node that cannot be linked to hovered node
47      * @param filteredNodesData
48      * @param nodesData
49      * @param cy
50      * @param hoveredNodeData
51      */
52     public fadeNonMachingComponents(filteredNodesData, nodesData, cy:Cy.Instance, hoveredNodeData?) {
53         let fadeNodes = _.xorWith(nodesData, filteredNodesData, (node1, node2) => {
54             return node1.id === node2.id;
55         });
56         if (hoveredNodeData) {
57             _.remove(fadeNodes, hoveredNodeData);
58         }
59         cy.batch(()=> {
60             _.each(fadeNodes, (node) => {
61                 cy.getElementById(node.id).style({'background-image-opacity': 0.4});
62             });
63         })
64     }
65
66     /**
67      * Resets all nodes to regular opacity
68      * @param cy
69      */
70     public resetFadedNodes(cy:Cy.Instance) {
71         cy.batch(()=> {
72             cy.nodes().style({'background-image-opacity': 1});
73         })
74     }
75
76     private static isRequirementFulfilled(fromNodeId:string, requirement:any, links:Array<CompositionCiLinkBase>):boolean {
77         return _.some(links, {
78             'relation': {
79                 'fromNode': fromNodeId,
80                 'relationships': [{
81                     'requirementOwnerId': requirement.ownerId,
82                     'requirement': requirement.name,
83                     'relationship': {
84                         'type': requirement.relationship
85                     }
86                 }
87                 ]
88             }
89         });
90     };
91
92     private static isMatch(requirement:Requirement, capability:Capability):boolean {
93         if (capability.type === requirement.capability) {
94             if (requirement.node) {
95                 if (_.includes(capability.capabilitySources, requirement.node)) {
96                     return true;
97                 }
98             } else {
99                 return true;
100             }
101         }
102         return false;
103     };
104
105     public getMatchedRequirementsCapabilities(fromComponentInstance:ComponentInstance,
106                                               toComponentInstance:ComponentInstance,
107                                               links:Array<CompositionCiLinkBase>):Array<Match> {
108         let fromToMatches:Array<Match> = this.getMatches(fromComponentInstance.requirements,
109             toComponentInstance.capabilities,
110             links,
111             fromComponentInstance.uniqueId,
112             toComponentInstance.uniqueId, true);
113         let toFromMatches:Array<Match> = this.getMatches(toComponentInstance.requirements,
114             fromComponentInstance.capabilities,
115             links,
116             fromComponentInstance.uniqueId,
117             toComponentInstance.uniqueId, false);
118
119         return fromToMatches.concat(toFromMatches);
120     }
121
122     /***** REFACTORED FUNCTIONS START HERE *****/
123
124     public getMatches(requirements:RequirementsGroup, capabilities:CapabilitiesGroup, links:Array<CompositionCiLinkBase>,
125                       fromId:string, toId:string, isFromTo: boolean):Array<Match> {
126         let matches:Array<Match> = [];
127         let unfulfilledReqs = this.getUnfulfilledRequirements(fromId, requirements, links);
128         _.forEach(unfulfilledReqs, (req)=> {
129             _.forEach(_.flatten(_.values(capabilities)), (capability:Capability)=> {
130                 if (MatchCapabilitiesRequirementsUtils.isMatch(req, capability)) {
131                     if(isFromTo) {
132                         matches.push(new Match(req, capability, isFromTo, fromId, toId));
133                     } else{
134                         matches.push(new Match(req, capability, isFromTo, toId, fromId));
135                     }
136                 }
137             });
138         });
139         return matches;
140     }
141
142     public getUnfulfilledRequirements = (fromNodeId:string, requirements:RequirementsGroup, links:Array<CompositionCiLinkBase>):Array<Requirement>=> {
143
144         let requirementArray:Array<Requirement> = [];
145         _.forEach(_.flatten(_.values(requirements)), (requirement:Requirement)=> {
146             if (requirement.name !== 'dependency' && requirement.parentName !== 'dependency' && !MatchCapabilitiesRequirementsUtils.isRequirementFulfilled(fromNodeId, requirement, links)) {
147                 requirementArray.push(requirement);
148             }
149         });
150         return requirementArray;
151     };
152
153
154     /**
155      * Returns true if there is a match between the capabilities and requirements that are passed in
156      * @param requirements
157      * @param capabilities
158      * @returns {boolean}
159      */
160     public containsMatch = (requirements:Array<Requirement>, capabilities:CapabilitiesGroup):boolean => {
161         return _.some(requirements, (req:Requirement)=> {
162             return _.some(_.flatten(_.values(capabilities)), (capability:Capability) => {
163                 return MatchCapabilitiesRequirementsUtils.isMatch(req, capability);
164             });
165         });
166     };
167
168     /**
169      * Returns array of nodes that can connect to the component.
170      * In order to connect, one of the following conditions must be met:
171      * 1. component has an unfulfilled requirement that matches a node's capabilities
172      * 2. node has an unfulfilled requirement that matches the component's capabilities
173      * 3. vl is passed in which has the capability to fulfill requirement from component and requirement on node.
174      */
175     public findMatchingNodes(component:Component, nodeDataArray:Array<CompositionCiNodeBase>,
176                              links:Array<CompositionCiLinkBase>):Array<any> //TODO allow for VL array and TEST
177     {
178         let componentRequirements:Array<Requirement> = this.getUnfulfilledRequirements(component.uniqueId, component.requirements, links);
179         return _.filter(nodeDataArray, (node:any)=> {
180             if (node && node.componentInstance) {
181
182                 //Check if component has an unfulfilled requirement that can be met by one of nodes's capabilities (#1)
183                 if (componentRequirements.length && node.category !== 'groupCp' && this.containsMatch(componentRequirements, node.componentInstance.capabilities)) {
184                     return true;
185
186                 } else { //Check if node has unfulfilled requirement that can be filled by component (#2)
187                     let nodeRequirements:Array<Requirement> = this.getUnfulfilledRequirements(node.componentInstance.uniqueId, node.componentInstance.requirements, links);
188                     if (!nodeRequirements.length) return false;
189                     if (this.containsMatch(nodeRequirements, component.capabilities)) {
190                         return true;
191                     }
192                 }
193             }
194         });
195     }
196 }
197
198 MatchCapabilitiesRequirementsUtils.$inject = [];