[SDC] rebase 1710
[sdc.git] / catalog-ui / src / app / directives / graphs-v2 / composition-graph / utils / composition-graph-nodes-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 {Component, NodesFactory, ComponentInstance, CompositionCiNodeVl,IAppMenu,AssetPopoverObj} from "app/models";
22 import {EventListenerService, LoaderService} from "app/services";
23 import {GRAPH_EVENTS,ModalsHandler,GraphUIObjects} from "app/utils";
24 import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
25 import {CommonGraphUtils} from "../../common/common-graph-utils";
26 /**
27  * Created by obarda on 11/9/2016.
28  */
29 export class CompositionGraphNodesUtils {
30     constructor(private NodesFactory:NodesFactory, private $log:ng.ILogService,
31                 private GeneralGraphUtils:CompositionGraphGeneralUtils,
32                 private commonGraphUtils:CommonGraphUtils,
33                 private eventListenerService:EventListenerService,
34                     private loaderService:LoaderService /*,
35                     private sdcMenu: IAppMenu,
36                     private ModalsHandler: ModalsHandler*/) {
37
38     }
39
40     /**
41      * Returns component instances for all nodes passed in
42      * @param nodes - Cy nodes
43      * @returns {any[]}
44      */
45     public getAllNodesData(nodes:Cy.CollectionNodes) {
46         return _.map(nodes, (node:Cy.CollectionFirstNode)=> {
47             return node.data();
48         })
49     };
50
51
52     public highlightMatchingNodesByName = (cy: Cy.Instance, nameToMatch: string) => {
53
54         cy.batch(() => {
55             cy.nodes("[name !@^= '" + nameToMatch + "']").style({ 'background-image-opacity': 0.4 });
56             cy.nodes("[name @^= '" + nameToMatch + "']").style({ 'background-image-opacity': 1 });
57         })
58         
59     }
60
61     //Returns all nodes whose name starts with searchTerm
62     public getMatchingNodesByName = (cy: Cy.Instance, nameToMatch: string): Cy.CollectionNodes => {
63         return cy.nodes("[name @^= '" + nameToMatch + "']");
64     };
65
66     /**
67      * Deletes component instances on server and then removes it from the graph as well
68      * @param cy
69      * @param component
70      * @param nodeToDelete
71      */
72     public deleteNode(cy:Cy.Instance, component:Component, nodeToDelete:Cy.CollectionNodes):void {
73
74         this.loaderService.showLoader('composition-graph');
75         let onSuccess:(response:ComponentInstance) => void = (response:ComponentInstance) => {
76             console.info('onSuccess', response);
77
78             //if node to delete is a UCPE, remove all children (except UCPE-CPs) and remove their "hostedOn" links
79             if (nodeToDelete.data().isUcpe) {
80                 _.each(cy.nodes('[?isInsideGroup]'), (node)=> {
81                     this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, nodeToDelete);
82                 });
83             }
84
85             //check whether the node is connected to any VLs that only have one other connection. If so, delete that VL as well
86             if (!(nodeToDelete.data() instanceof CompositionCiNodeVl)) {
87                 let connectedVls:Array<Cy.CollectionFirstNode> = this.getConnectedVlToNode(nodeToDelete);
88                 this.handleConnectedVlsToDelete(connectedVls);
89             }
90
91             //update UI
92             cy.remove(nodeToDelete);
93
94         };
95
96         let onFailed:(response:any) => void = (response:any) => {
97             console.info('onFailed', response);
98         };
99
100
101         this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
102             () => component.deleteComponentInstance(nodeToDelete.data().componentInstance.uniqueId).then(onSuccess, onFailed),
103             () => this.loaderService.hideLoader('composition-graph')
104         );
105
106     };
107
108 /*
109         public confirmDeleteNode = (nodeId:string, cy:Cy.Instance, component:Component) => {
110             let node:Cy.CollectionNodes = cy.getElementById(nodeId);
111             let onOk = ():void => {
112                 this.deleteNode(cy, component, node);
113             };
114
115             let componentInstance:ComponentInstance = node.data().componentInstance;
116             let state = "deleteInstance";
117             let title:string =  this.sdcMenu.alertMessages[state].title;
118             let message:string =  this.sdcMenu.alertMessages[state].message.format([componentInstance.name]);
119
120             this.ModalsHandler.openAlertModal(title, message).then(onOk);
121         };*/
122     /**
123      * Finds all VLs connected to a single node
124      * @param node
125      * @returns {Array<Cy.CollectionFirstNode>}
126      */
127     public getConnectedVlToNode = (node:Cy.CollectionNodes):Array<Cy.CollectionFirstNode> => {
128         let connectedVls:Array<Cy.CollectionFirstNode> = new Array<Cy.CollectionFirstNode>();
129         _.forEach(node.connectedEdges().connectedNodes(), (node:Cy.CollectionFirstNode) => {
130             if (node.data() instanceof CompositionCiNodeVl) {
131                 connectedVls.push(node);
132             }
133         });
134         return connectedVls;
135     };
136
137
138     /**
139      * Delete all VLs that have only two connected nodes (this function is called when deleting a node)
140      * @param connectedVls
141      */
142     public handleConnectedVlsToDelete = (connectedVls:Array<Cy.CollectionFirstNode>) => {
143         _.forEach(connectedVls, (vlToDelete:Cy.CollectionNodes) => {
144
145             if (vlToDelete.connectedEdges().length === 2) { // if vl connected only to 2 nodes need to delete the vl
146                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, vlToDelete.data().componentInstance);
147             }
148         });
149     };
150
151
152     /**
153      * This function is called when moving a node in or out of UCPE.
154      * Deletes all connected VLs that have less than 2 valid connections remaining after the move
155      * Returns the collection of vls that are in the process of deletion (async) to prevent duplicate calls while deletion is in progress
156      * @param component
157      * @param cy
158      * @param node - node that was moved in/out of ucpe
159      */
160     public deleteNodeVLsUponMoveToOrFromUCPE = (component:Component, cy:Cy.Instance, node:Cy.CollectionNodes):Cy.CollectionNodes => {
161         if (node.data() instanceof CompositionCiNodeVl) {
162             return;
163         }
164
165         let connectedVLsToDelete:Cy.CollectionNodes = cy.collection();
166         _.forEach(node.neighborhood('node'), (connectedNode) => {
167
168             //Find all neighboring nodes that are VLs
169             if (connectedNode.data() instanceof CompositionCiNodeVl) {
170
171                 //check VL's neighbors to see if it has 2 or more nodes whose location is compatible with VL (regardless of whether VL is in or out of UCPE)
172                 let compatibleNodeCount = 0;
173                 let vlNeighborhood = connectedNode.neighborhood('node');
174                 _.forEach(vlNeighborhood, (vlNeighborNode)=> {
175                     if (this.commonGraphUtils.nodeLocationsCompatible(cy, connectedNode, vlNeighborNode)) {
176                         compatibleNodeCount++;
177                     }
178                 });
179
180                 if (compatibleNodeCount < 2) {
181                     connectedVLsToDelete = connectedVLsToDelete.add(connectedNode);
182                 }
183             }
184         });
185
186         connectedVLsToDelete.each((i, vlToDelete:Cy.CollectionNodes)=> {
187             this.deleteNode(cy, component, vlToDelete);
188         });
189         return connectedVLsToDelete;
190     };
191
192     /**
193      * This function will update nodes position. if the new position is into or out of ucpe, the node will trigger the ucpe events
194      * @param cy
195      * @param component
196      * @param nodesMoved - the node/multiple nodes now moved by the user
197      */
198     public onNodesPositionChanged = (cy:Cy.Instance, component:Component, nodesMoved:Cy.CollectionNodes):void => {
199
200         if (nodesMoved.length === 0) {
201             return;
202         }
203
204         let isValidMove:boolean = this.GeneralGraphUtils.isGroupValidDrop(cy, nodesMoved);
205         if (isValidMove) {
206
207             this.$log.debug(`composition-graph::ValidDrop:: updating node position`);
208             let instancesToUpdateInNonBlockingAction:Array<ComponentInstance> = new Array<ComponentInstance>();
209
210             _.each(nodesMoved, (node:Cy.CollectionFirstNode)=> {  //update all nodes new position
211
212                 if (node.data().isUcpePart && !node.data().isUcpe) {
213                     return;
214                 }//No need to update UCPE-CPs
215
216                 //update position
217                 let newPosition:Cy.Position = this.commonGraphUtils.getNodePosition(node);
218                 node.data().componentInstance.updatePosition(newPosition.x, newPosition.y);
219
220                 //check if node moved to or from UCPE
221                 let ucpe = this.commonGraphUtils.isInUcpe(node.cy(), node.boundingbox());
222                 if (node.data().isInsideGroup || ucpe.length) {
223                     this.handleUcpeChildMove(node, ucpe, instancesToUpdateInNonBlockingAction);
224                 } else {
225                     instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
226                 }
227
228             });
229
230             if (instancesToUpdateInNonBlockingAction.length > 0) {
231                 this.GeneralGraphUtils.pushMultipleUpdateComponentInstancesRequestToQueue(false, instancesToUpdateInNonBlockingAction, component);
232             }
233         } else {
234             this.$log.debug(`composition-graph::notValidDrop:: node return to latest position`);
235             //reset nodes position
236             nodesMoved.positions((i, node) => {
237                 return {
238                     x: +node.data().componentInstance.posX,
239                     y: +node.data().componentInstance.posY
240                 };
241             })
242         }
243
244         this.GeneralGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(() => {
245         }, () => {
246             this.loaderService.hideLoader('composition-graph');
247         });
248
249     };
250
251     /**
252      * Checks whether the node has been added or removed from UCPE and triggers appropriate events
253      * @param node - node moved
254      * @param ucpeContainer - UCPE container that the node has been moved to. When moving a node out of ucpe, param will be empty
255      * @param instancesToUpdateInNonBlockingAction
256      */
257     public handleUcpeChildMove(node:Cy.CollectionFirstNode, ucpeContainer:Cy.CollectionElements, instancesToUpdateInNonBlockingAction:Array<ComponentInstance>) {
258
259         if (node.data().isInsideGroup) {
260             if (ucpeContainer.length) { //moving node within UCPE. Simply update position
261                 this.commonGraphUtils.updateUcpeChildPosition(<Cy.CollectionNodes>node, ucpeContainer);
262                 instancesToUpdateInNonBlockingAction.push(node.data().componentInstance);
263             } else { //removing node from UCPE. Notify observers
264                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_REMOVE_NODE_FROM_UCPE, node, ucpeContainer);
265             }
266         } else if (!node.data().isInsideGroup && ucpeContainer.length && !node.data().isUcpePart) { //adding node to UCPE
267             this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_INSERT_NODE_TO_UCPE, node, ucpeContainer, true);
268         }
269     }
270         /**
271          * Gets the position for the asset popover menu
272          * Then, check if right edge of menu would overlap horizontal screen edge (palette offset + canvas width - right panel)
273          * Then, check if bottom edge of menu would overlap the vertical end of the canvas.
274          * @param cy
275          * @param node
276          * @returns {Cy.Position}
277         
278         public createAssetPopover = (cy: Cy.Instance, node:Cy.CollectionFirstNode, isViewOnly:boolean):AssetPopoverObj => {
279
280             let menuOffset:Cy.Position = { x: node.renderedWidth() / 2, y: -(node.renderedWidth() / 2) };// getNodePositionWithOffset returns central point of node. First add node.renderedWidth()/2 to get its to border.
281             let menuPosition:Cy.Position = this.commonGraphUtils.getNodePositionWithOffset(node, menuOffset);
282             let menuSide:string = 'right';
283
284             if(menuPosition.x + GraphUIObjects.COMPOSITION_NODE_MENU_WIDTH >= cy.width() + GraphUIObjects.DIAGRAM_PALETTE_WIDTH_OFFSET - GraphUIObjects.COMPOSITION_RIGHT_PANEL_OFFSET){
285                 menuPosition.x -= menuOffset.x * 2 + GraphUIObjects.COMPOSITION_NODE_MENU_WIDTH; //menu position already includes offset to the right. Therefore, subtract double offset so we have same distance from node for menu on left
286                 menuSide = 'left';
287             }
288
289             if(menuPosition.y + GraphUIObjects.COMPOSITION_NODE_MENU_HEIGHT >= cy.height()){
290                 menuPosition.y = menuPosition.y - GraphUIObjects.COMPOSITION_NODE_MENU_HEIGHT - menuOffset.y * 2;
291             }
292
293             return new AssetPopoverObj(node.data().id, node.data().name, menuPosition, menuSide, isViewOnly);
294         };
295  */
296
297     }
298
299
300     CompositionGraphNodesUtils.$inject = ['NodesFactory', '$log', 'CompositionGraphGeneralUtils', 'CommonGraphUtils', 'EventListenerService', 'LoaderService' /*, 'sdcMenu', 'ModalsHandler'*/]
301