19a5f6d155f659c15f92330f8bcab5bd2fde94f2
[appc/cdt.git] / src / app / vnfs / build-artifacts / parameter-definitions / parameter.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5
6 Copyright (C) 2018 IBM Intellectual Property. All rights reserved.
7 ===================================================================
8 Copyright (C) 2018 IBM.
9 ===================================================================
10
11 Unless otherwise specified, all software contained herein is licensed
12 under the Apache License, Version 2.0 (the License);
13 you may not use this software except in compliance with the License.
14 You may obtain a copy of the License at
15
16     http://www.apache.org/licenses/LICENSE-2.0
17
18 Unless required by applicable law or agreed to in writing, software
19 distributed under the License is distributed on an "AS IS" BASIS,
20 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 See the License for the specific language governing permissions and
22 limitations under the License.
23
24 ============LICENSE_END============================================
25 */
26
27 import { Component, OnInit, ViewChild } from '@angular/core';
28 import { saveAs } from 'file-saver';
29 import { ParamShareService } from '../../../shared/services/paramShare.service';
30 import { MappingEditorService } from '../../../shared/services/mapping-editor.service';
31 import { ModalComponent } from '../../../shared/modal/modal.component';
32 import { HttpUtilService } from '../../../shared/services/httpUtil/http-util.service';
33 import { UtilityService } from '../../../shared/services/utilityService/utility.service';
34 import { environment } from '../../../../environments/environment';
35 import { NotificationsService } from 'angular2-notifications';
36 import { ParameterDefinitionService } from './parameter-definition.service';
37 import 'rxjs/add/operator/map';
38 import { NgProgress } from 'ngx-progressbar';
39 import { NgxSpinnerService } from 'ngx-spinner';
40 import { appConstants } from '../../../../constants/app-constants';
41
42 let YAML = require('yamljs');
43
44 declare var $: any;
45
46 @Component({
47     selector: 'parameter-form',
48     templateUrl: './parameter.component.html',
49     styleUrls: ['../reference-dataform/reference-dataform.component.css'],
50     providers: [ParameterDefinitionService]
51 })
52 export class ParameterComponent implements OnInit {
53     public paramForm: any;
54     public actionType: any;
55     public showFilterFields: boolean;
56     public filterByFieldvalues = appConstants.filterByFieldvalues;
57     public ruleTypeConfiguaration = appConstants.ruleTypeConfiguaration;
58     public requiredValues: boolean[] = appConstants.requiredValues;
59     public sourceValues = appConstants.sourceValues;
60     public ruleTypeValues = appConstants.ruleTypeValues;
61     public typeValues = appConstants.typeValues;
62     public responseKeyNameValues = appConstants.responseKeyNameValues;
63     public responseKeyValues = appConstants.responseKeyValues;
64     public requestKeyNameValues = appConstants.requestKeyNameValues;
65     public requestKeyValues = appConstants.requestKeyValues;
66     public myKeyFileName = null;
67     public myPdFileName = null;
68     public disposable: any;
69     public confirmation: boolean;
70     public showConfirmation: boolean;
71     public test: boolean;
72     apiToken = localStorage['apiToken'];
73     userId = localStorage['userId'];
74     public initialData: any;
75     public intialData: any;
76     public initialAction: any;
77     public item: any = {};
78     public subscription: any;
79     public Actions = [
80         { action: appConstants.Actions.configBackup, value: appConstants.Actions.configBackup },
81         { action: appConstants.Actions.ConfigModify, value: appConstants.Actions.ConfigModify },
82         { action: appConstants.Actions.configRestore, value: appConstants.Actions.configRestore },
83         { action: appConstants.Actions.configure, value: appConstants.Actions.configure },
84         { action: appConstants.Actions.getRunningConfig, value: appConstants.Actions.getRunningConfig },
85         { action: appConstants.Actions.healthCheck, value: appConstants.Actions.healthCheck },
86         { action: appConstants.Actions.startApplication, value: appConstants.Actions.startApplication },
87         { action: appConstants.Actions.stopApplication, value: appConstants.Actions.stopApplication }
88     ];
89     public uploadTypes = appConstants.uploadTypes;
90
91     options = appConstants.optionsToNotificationComponent;
92     public vnfcTypeData: string = '';
93     public selectedUploadType: string;
94     @ViewChild(ModalComponent) modalComponent: ModalComponent;
95     public title: string;
96     public parameterDefinitionMap: { [index: string]: string; } = {};
97     public parameterNameValues = {};
98     public displayParamObjects;
99     public modelParamDefinitionObjects;
100     public vnfType: any;
101     vnfcType: any;
102     protocol: any;
103     public refNameObj = {};
104     public action;
105     public artifactName;
106     public appDataObject: any;
107     public downloadDataObject: any;
108     public artifact_fileName = "";
109     identifier: any;
110     private selectedActionReference: any;
111
112     constructor(private httpService: HttpUtilService,
113         private parameterDefinitionService: ParameterDefinitionService,
114         private paramShareService: ParamShareService,
115         private mappingEditorService: MappingEditorService,
116         private httpUtil: HttpUtilService,
117         private utilService: UtilityService,
118         private nService: NotificationsService,
119         private ngProgress: NgProgress,
120         private spinner: NgxSpinnerService) {
121     }
122
123     ngOnInit() {
124         this.selectedActionReference = this.parameterDefinitionService.prepareFileName();
125         if (this.selectedActionReference && this.selectedActionReference != undefined) {
126
127             this.vnfType = this.selectedActionReference.scope['vnf-type'];
128             this.vnfcType = this.selectedActionReference.scope['vnfc-type'];
129             this.protocol = this.selectedActionReference['device-protocol'];
130             this.action = this.selectedActionReference.action;
131
132             for (let i = 0; i < this.selectedActionReference['artifact-list'].length; i++) {
133                 let artifactList = this.selectedActionReference['artifact-list'];
134                 if (artifactList[i]['artifact-type'] === 'parameter_definitions') {
135                     var artifactName = artifactList[i]['artifact-name'];
136                     var artifactNameWithoutExtension = '';
137                     if (artifactName) {
138                         artifactNameWithoutExtension = artifactName.substring(0, artifactName.lastIndexOf("."));
139                     }
140                     if (this.mappingEditorService.identifier) {
141                         if (artifactNameWithoutExtension.endsWith(this.mappingEditorService.identifier)) {
142                             this.artifact_fileName = artifactName;
143                         }
144
145                     }
146                     else {
147                         this.artifact_fileName = artifactName;
148                     }
149                 }
150             }
151             this.parameterDefinitionService.setValues(this.vnfType, this.vnfcType, this.protocol, this.action, this.artifact_fileName);
152         }
153         else {
154             this.selectedActionReference = {
155                 'action': '',
156                 'scope': { 'vnf-type': '', 'vnfc-type': '' },
157                 'vm': [],
158                 'protocol': '',
159                 'download-dg-reference': '',
160                 'user-name': '',
161                 'port-number': '',
162                 'artifact-list': [],
163                 'deviceTemplate': '',
164                 'scopeType': ''
165             };
166         }
167
168         this.identifier = this.mappingEditorService.identifier;
169     }
170
171     ngAfterViewInit() {
172         if (this.mappingEditorService.latestAction) {
173             this.displayParamObjects = [];
174             this.modelParamDefinitionObjects = [];
175             if (this.paramShareService.getSessionParamData() != undefined && this.paramShareService.getSessionParamData().length > 0) {
176                 this.getPDFromSession();
177             } else {
178                 this.ngProgress.start();
179                 this.getPD();
180                 setTimeout(() => {
181                 this.ngProgress.done();
182             }, 3500);
183             }
184         } else {
185             this.nService.error(appConstants.errors.error, appConstants.errors["noAction&VNFTypeInRDscreenError"]);
186         }
187         return this.displayParamObjects;
188     }
189
190
191     public getPD() {
192         let result: any;
193         let input=this.utilService.createPayloadForRetrieve(false, this.action, this.vnfType,this.artifact_fileName);
194         let artifactContent: any;
195         return this.httpService.post({
196             url: environment.getDesigns,
197             data: input
198         }).subscribe(data => {
199             if (this.utilService.checkResult(data)) {
200                 let result: any = JSON.parse(data.output.data.block).artifactInfo[0];
201                 var pdObject = YAML.parse(result['artifact-content']);
202                 let fileModel = pdObject['vnf-parameter-list'];
203                 this.displayParamObjects = this.parameterDefinitionService.populatePD(fileModel);
204             }
205                        
206         },
207
208             error => this.nService.error(appConstants.errors.error, appConstants.errors.connectionError));
209
210     }
211
212     public getPDFromSession() {
213
214         this.ngProgress.start();
215         return this.httpService.get({
216             url: 'testurl',
217         }).subscribe(data => {
218             this.displayParamObjects = this.paramShareService.getSessionParamData();
219             this.ngProgress.done();
220         },
221             error => {
222                 this.displayParamObjects = this.paramShareService.getSessionParamData();
223                 this.ngProgress.done();
224             });
225     }
226
227     //========================== End of NGInit() Method============================================
228     selectedNavItem(item: any) {
229         this.item = item;
230     }
231
232     //========================== End of selectedNavItem() Method============================================
233     browsePdFile() {
234         $('#inputFile1').trigger('click');
235     }
236
237     //========================== End of browsePdFile() Method============================================
238     browseKeyFile() {
239         $('#inputFile2').trigger('click');
240
241     }
242
243     //========================== End of browseKeyFile() Method============================================
244
245
246     //========================== End of appendSlashes() Method============================================
247
248
249     //========================== End of prepareFileName() Method============================================
250     ngOnDestroy() {
251         this.parameterDefinitionService.destroy(this.displayParamObjects);
252     }
253
254     //========================== End of ngOnDestroy() Method============================================
255
256     public showUpload() {
257         this.selectedUploadType = this.uploadTypes[0].value;
258     };
259
260     //========================== End of showUpload() Method============================================
261     //This is called when the user selects new files from the upload button
262     public fileChange(input, uploadType) {
263         if (input.files && input.files[0]) {
264             this.spinner.show();
265             // Create the file reader
266             let reader = new FileReader();
267             this.readFile(input.files[0], reader, (result) => {
268                 if ('pdfile' === uploadType) {
269                     this.myPdFileName = input.files[0].name;
270                     this.displayParamObjects = this.parameterDefinitionService.processPDfile(this.myPdFileName, result);
271                 }
272             });
273             setTimeout(() => {
274                         /** spinner ends after 3.5 seconds */
275                         this.spinner.hide();
276           }, 3500);
277         }
278     }
279
280     //========================== End of fileChange() Method============================================
281     public readFile(file, reader, callback) {
282         // Set a callback funtion to fire after the file is fully loaded
283         reader.onload = () => {
284             // callback with the results
285             callback(reader.result);
286         };
287         // Read the file
288         reader.readAsText(file, 'UTF-8');
289     }
290
291     //========================== End of readFile() Method============================================
292     fileChangeEvent(fileInput: any) {
293         let obj: any = fileInput.target.files;
294     }
295
296
297     sourceChanged(data, obj) {
298         if (data == 'A&AI') {
299             obj.ruleTypeValues = appConstants.ruleTypeValues;
300             for (let x = 0; x < 5; x++) {
301                 obj['response-keys'][x]['key-name'] = null;
302                 obj['response-keys'][x]['key-value'] = null;
303             }
304         } else if (data == 'Manual') {
305             obj.ruleTypeValues = [null];
306             obj['rule-type'] = null;
307             obj.showFilterFields = false;
308             for (let x = 0; x < 5; x++) {
309                 obj['response-keys'][x]['key-name'] = null;
310                 obj['response-keys'][x]['key-value'] = null;
311             }
312         }
313         else {
314             obj.ruleTypeValues = [null];
315         }
316     }
317
318     //========================== End of sourceChanged() Method============================================
319     ruleTypeChanged(data, obj) {
320         if (data == null || data == undefined || data == 'null') {
321             obj.showFilterFields = false;
322             obj['rule-type'] = null;
323             for (let x = 0; x < 5; x++) {
324                 obj['response-keys'][x]['key-name'] = null;
325                 obj['response-keys'][x]['key-value'] = null;
326             }
327         } else {
328             let sourceObject = this.ruleTypeConfiguaration[data];
329             if (data == 'vm-name-list' || data == 'vnfc-name-list' || data == 'vnfc-oam-ipv4-address-list') {
330                 this.showFilterFields = false;
331                 obj.showFilterFields = true;
332                 this.filetrByFieldChanged(obj['response-keys'][3]['key-value'], obj);
333             } else {
334                 obj.showFilterFields = false;
335                 obj['response-keys'][3]['key-name'] = null;
336                 obj['response-keys'][3]['key-value'] = null;
337                 obj['response-keys'][4]['key-name'] = null;
338                 obj['response-keys'][4]['key-value'] = null;
339             }
340             for (let x = 0; x < sourceObject.length; x++) {
341                 obj['response-keys'][x]['key-name'] = sourceObject[x]['key-name'];
342                 obj['response-keys'][x]['key-value'] = sourceObject[x]['key-value'];
343             }
344         }
345
346     }
347
348     //========================== End of ruleTypeChanged() Method============================================
349     filetrByFieldChanged(data, obj) {
350         if (data == null || data == undefined || data == 'null') {
351             obj.enableFilterByValue = false;
352             obj['response-keys'][4]['key-value'] = null;
353         } else {
354             obj.enableFilterByValue = true;
355         }
356
357     }
358
359
360 }