Catalog alignment
[sdc.git] / catalog-ui / src / app / ng2 / pages / composition / panel / panel-tabs / policy-targets-tab / policy-targets-tab.component.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 { Component, Input, Output, EventEmitter, OnChanges, HostBinding, OnDestroy, OnInit } from "@angular/core";
23 import { TranslateService } from './../../../../../shared/translator/translate.service';
24 import { PoliciesService } from "../../../../../services/policies.service";
25 import { PolicyInstance } from './../../../../../../models/graph/zones/policy-instance';
26 import { SdcUiComponents, SdcUiCommon, SdcUiServices } from "onap-ui-angular";
27 import { AddElementsComponent } from "../../../../../components/ui/modal/add-elements/add-elements.component";
28 import { TargetUiObject } from "../../../../../../models/ui-models/ui-target-object";
29 import { ComponentInstance } from "../../../../../../models/componentsInstances/componentInstance";
30 import { TargetOrMemberType } from "../../../../../../utils/constants";
31 import { GRAPH_EVENTS } from 'app/utils';
32 import { EventListenerService } from 'app/services/event-listener-service';
33 import { CompositionService } from "app/ng2/pages/composition/composition.service";
34 import { WorkspaceService } from "app/ng2/pages/workspace/workspace.service";
35 import { Store } from "@ngxs/store";
36 import { Select } from "@ngxs/store";
37 import { Observable } from "rxjs";
38 import { tap } from "rxjs/operators";
39 import {GraphState} from "../../../common/store/graph.state";
40
41 @Component({
42     selector: 'policy-targets-tab',
43     templateUrl: './policy-targets-tab.component.html',
44     styleUrls: ['policy-targets-tab.component.less']
45 })
46  
47 export class PolicyTargetsTabComponent implements OnInit {
48
49     @Input() input:any;
50
51
52     @Input() isViewOnly: boolean;
53     @HostBinding('class') classes = 'component-details-panel-tab-policy-targets';
54     @Select(GraphState.getSelectedComponent) policy$: Observable<PolicyInstance>;
55     public policy: PolicyInstance;
56     private subscription;
57     
58     private addModalInstance: SdcUiComponents.ModalComponent;
59     public targets: Array<TargetUiObject>; // UI object to hold all targets with names.
60
61
62     constructor(private translateService: TranslateService,
63         private policiesService: PoliciesService,
64         private modalService: SdcUiServices.ModalService,
65         private eventListenerService: EventListenerService,
66         private compositionService: CompositionService,
67         private workspaceService: WorkspaceService,
68         private loaderService: SdcUiServices.LoaderService,
69         private store: Store
70     ) { }
71
72     ngOnInit() {
73         this.subscription = this.policy$.pipe(
74             tap((policy) => {
75                 if(policy instanceof PolicyInstance){
76                     this.policy = policy;
77                     this.targets = this.policy.getTargetsAsUiObject(<ComponentInstance[]>this.compositionService.componentInstances, this.compositionService.groupInstances);                      
78                 }
79             })).subscribe(); 
80     }
81
82     ngOnDestroy () {
83         if(this.subscription)
84             this.subscription.unsubscribe();
85     }
86
87     deleteTarget(target: TargetUiObject): void {
88         this.loaderService.activate();
89         this.policiesService.deletePolicyTarget(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.policy, target.uniqueId, target.type).subscribe(
90             (policyInstance:PolicyInstance) => {
91                 this.targets = this.targets.filter(item => item.uniqueId !== target.uniqueId);
92                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_POLICY_INSTANCE_UPDATE, policyInstance);
93                 // this.store.dispatch(new UpdateSelectedComponentAction({uniqueId: policyInstance.uniqueId, type:ComponentType.}));
94             },
95             error => {
96                 console.log("Error deleting target!");
97                 this.loaderService.deactivate();
98             },
99             () => this.loaderService.deactivate()
100         );
101     }
102
103    
104     addTargets = ():void => {
105         
106         var targetsToAdd:Array<TargetUiObject> = this.addModalInstance.innerModalContent.instance.existingElements; //TODO refactor sdc-ui modal in order to return the data
107         if(targetsToAdd.length > 0) {
108             this.addModalInstance.closeModal();
109             this.loaderService.activate();
110             var updatedTargets: Array<TargetUiObject> = _.union(this.targets, targetsToAdd);
111             this.policiesService.updateTargets(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.policy.uniqueId, updatedTargets).subscribe(
112                 (updatedPolicyInstance:PolicyInstance) => {
113                     this.targets = updatedTargets;
114                     this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_POLICY_INSTANCE_UPDATE, updatedPolicyInstance);
115                     // this.store.dispatch(new UpdateSelectedComponentAction({component: updatedPolicyInstance}));
116                 },
117                 error => {
118                     console.log("Error updating targets!");
119                     this.loaderService.deactivate();
120                 },
121                 () => this.loaderService.deactivate()
122             );
123         }
124     }
125
126     getOptionalsTargetsToAdd():Array<TargetUiObject> {
127         let optionalsTargetsToAdd:Array<TargetUiObject> = [];
128         // adding all instances as optional targets to add if not already exist
129         _.forEach(this.compositionService.componentInstances, (instance:ComponentInstance) => {
130             if (!_.some(this.targets, (target:TargetUiObject) => {
131                     return target.uniqueId === instance.uniqueId
132                 })) {
133                 optionalsTargetsToAdd.push(new TargetUiObject(instance.uniqueId, TargetOrMemberType.COMPONENT_INSTANCES, instance.name));
134             }
135         });
136
137         // adding all groups as optional targets to add if not already exist
138         _.forEach(this.compositionService.groupInstances, (groupInstance:ComponentInstance) => { // adding all instances as optional targets to add if not already exist
139             if (!_.some(this.targets, (target:TargetUiObject) => {
140                     return target.uniqueId === groupInstance.uniqueId
141                 })) {
142                 optionalsTargetsToAdd.push(new TargetUiObject(groupInstance.uniqueId, TargetOrMemberType.GROUPS, groupInstance.name));
143             }
144         });
145
146         return optionalsTargetsToAdd;
147     }
148
149     openAddTargetModal(): void {
150         let addTargetModalConfig = {
151             title: this.policy.name + " ADD TARGETS",
152             size: "md",
153             type: SdcUiCommon.ModalType.custom,
154             testId: "addTargetsModal",
155             buttons: [
156                 {text: "ADD TARGETS", size: 'xsm', callback: this.addTargets, closeModal: false},
157                 {text: 'CANCEL', size: 'sm', type: "secondary", closeModal: true}
158             ]
159         } as SdcUiCommon.IModalConfig;
160         var optionalTargetsToAdd = this.getOptionalsTargetsToAdd();
161         this.addModalInstance = this.modalService.openCustomModal(addTargetModalConfig, AddElementsComponent, {
162             elementsToAdd: optionalTargetsToAdd,
163             elementName: "target"
164         });
165     }
166 }