added progress spinner while uploading template
[appc/cdt.git] / src / app / vnfs / build-artifacts / template-holder / template-configuration / template-configuration.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
6 Copyright (C) 2018 IBM.
7 ===================================================================
8
9 Unless otherwise specified, all software contained herein is licensed
10 under the Apache License, Version 2.0 (the License);
11 you may not use this software except in compliance with the License.
12 You may obtain a copy of the License at
13
14     http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 ============LICENSE_END============================================
23 */
24
25 import { Component, Input, OnInit, ViewChild } from '@angular/core';
26 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
27 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
28 import { ArtifactRequest } from '../../../../shared/models/index';
29 import { ActivatedRoute, Router } from '@angular/router';
30 import { saveAs } from 'file-saver';
31 import { NotificationService } from '../../../../shared/services/notification.service';
32 import { NotificationsService } from 'angular2-notifications';
33 import { ParamShareService } from '../../../../shared/services/paramShare.service';
34 import { DialogService } from 'ng2-bootstrap-modal';
35 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
36 import { BuildDesignComponent } from '../../build-artifacts.component';
37 import { environment } from '../../../../../environments/environment';
38 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
39 import { NgProgress } from 'ngx-progressbar';
40 import { NgxSpinnerService } from 'ngx-spinner';
41 declare var $: any
42
43 @Component({ selector: 'app-golden-configuration', templateUrl: './template-configuration.component.html', styleUrls: ['./template-configuration.component.css'] })
44 export class GoldenConfigurationComponent implements OnInit {
45   @ViewChild('templateeditor') templateeditor;
46   @Input() configMappingEditorContent: string;
47   @Input() isMappingComp: boolean;
48   @ViewChild('myInput') myInputVariable: any;
49   @ViewChild('myModal') modal: ModalComponent;
50   aceText: string = ""
51   fileName: string = ""
52   showTemplateVersionDiv: any;
53   downloadedTemplateFileName: any;
54   downloadedParamFileName: any;
55   templateVersionNo: any = '0.0.1';
56   saveToGuiCacheFlag = 'false';
57   initialAction: any;
58   public referenceData: Array<Object> = [];
59   public scopeName: any;
60   public subscription: any;
61   public item: any = {};
62   public goldenActions: Array<string> = [];
63   public refNameObj = {};
64   public action = '';
65   public artifactName = '';
66   public type;
67   public showError: boolean = false;
68   public tempretrieveFlag: boolean = false;
69   public fileNameForTempSave;
70   initialData: any;
71   showDownloadDiv: boolean = false;
72   downloadType: any;
73   enableBrowse: boolean = true;
74   enableMerge: boolean = false;
75   uploadValidationSuccess: boolean = false;
76   fileExtension: any = "xml";
77   apiToken = localStorage['apiToken'];
78   public appDataObject: any;
79   public downloadDataObject: any;
80   public checkNameEntered: boolean = true;
81   public selectedWord: any = this.mappingEditorService.getSelectedWord();
82   public Actions = [
83     { action: "ConfigBackup", value: "ConfigBackup" },
84     { action: "ConfigModify", value: "ConfigModify" },
85     { action: "ConfigRestore", value: "ConfigRestore" },
86     { action: "Configure", value: "Configure" },
87     { action: "GetRunningConfig", value: "GetRunningConfig" },
88     { action: "HealthCheck", value: "HealthCheck" },
89     { action: "StartApplication", value: "StartApplication" },
90     { action: "StopApplication", value: "StopApplication" }
91   ];
92   options = {
93     timeOut: 1000,
94     showProgressBar: true,
95     pauseOnHover: true,
96     clickToClose: true,
97     maxLength: 200
98   }
99   public replaceWord;
100   public enableDownloadButtons: boolean = false;
101   constructor(
102     private buildDesignComponent: BuildDesignComponent, 
103     private paramShareService: ParamShareService, 
104     private dialogService: DialogService, 
105     private notificationService: NotificationService, 
106     private httpUtil: HttpUtilService, 
107     private mappingEditorService: MappingEditorService, 
108     private activeRoutes: ActivatedRoute, 
109     private router: Router, 
110     private nService: NotificationsService, 
111     private ngProgress: NgProgress,
112     private spinner: NgxSpinnerService) {
113     this.artifactRequest.action = '';
114     this.artifactRequest.version = '';
115     this.artifactRequest.paramsContent = '{}';
116     this.artifactRequest.paramKeysContent = '';
117   }
118   public templateEditor: any;
119   public fileType: any = '';
120   public actionType: any;
121   public myfileName: any;
122   userId = localStorage['userId'];
123   public artifactRequest: ArtifactRequest = new ArtifactRequest();
124   public showUploadStatus: boolean = false;
125   public uploadStatus: boolean = false;
126   public uploadTypes = [
127     {
128       value: 'Generated Template',
129       display: 'Sample Json Param File'
130     },
131     {
132       value: 'Mapping Data',
133       display: 'Sample Json Param File'
134     }
135   ];
136   vnfType: any = '';
137   vnfcType: any = '';
138   protocol: any = '';
139   refObj: any;
140   editor: any;
141   editorContent: any;
142   tempName: any;
143   enableValidateTemplate: boolean = false;;
144   public selectedUploadType: string = this.uploadTypes[0].value;
145   identifier: any;
146   public tempRetrievalResponse: any;
147   public mergeStatus: boolean = false;
148
149   //======================================Start of ngOnInit() Method============================================
150   ngOnInit() {
151     var refObj = this.refObj = this.prepareFileName();
152     if (refObj && refObj != undefined) {
153       this.item = refObj;
154
155       this.vnfType = this.item.scope["vnf-type"];
156       this.vnfcType = this.item.scope["vnfc-type"];
157       this.protocol = this.item['device-protocol'];
158       this.action = this.item.action;
159       this.artifactRequest.action = this.item.action;
160       this.artifactRequest.vnfType = this.vnfType;
161       if (this.vnfcType != undefined && this.vnfcType.length != 0) {
162         this.scopeName = this.vnfcType;
163       }
164       else {
165         this.scopeName = this.vnfType;
166       }
167     }
168     else {
169       this.item = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
170     }
171     this.initialAction = this.item.action;
172     this.activeRoutes.url.subscribe(UrlSegment => {
173       this.actionType = UrlSegment[0].path
174     })
175     this.mappingEditorService.fromScreen = 'MappingScreen';
176     this.identifier = this.mappingEditorService.identifier;
177   }
178   //========================== End of ngOnInit() Method============================================
179   ngOnDestroy() {
180     if (this.refObj && this.refObj != undefined) {
181       if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
182         this.saveTemplate();
183         this.prepareAppData();
184         this.prepareDownloadData();
185         this.mappingEditorService.changeNavAppData(this.appDataObject);
186         this.mappingEditorService.changeNavDownloadData(this.downloadDataObject);
187       }
188     }
189   }
190   //========================== End of ngOnDestroy() Method============================================
191   ngAfterViewInit() {
192     if (this.mappingEditorService.latestAction) {
193       this.refNameObj = this.mappingEditorService.latestAction;
194       if (this.vnfcType !== 'null') {
195         this.type = this.vnfcType;
196       }
197       else {
198         this.type = this.vnfType;
199       }
200       for (let i = 0; i < this.refNameObj['artifact-list'].length; i++) {
201         let artifactList = this.refNameObj['artifact-list'];
202         if (artifactList[i]['artifact-type'] === 'config_template') {
203           var artifactName = artifactList[i]['artifact-name'];
204           var artifactNameWithoutExtension = '';
205                     if (artifactName) {
206             artifactNameWithoutExtension = artifactName.substring(0, artifactName.lastIndexOf("."));
207           }
208           if(this.mappingEditorService.identifier) {
209             if(artifactNameWithoutExtension.endsWith(this.mappingEditorService.identifier)) {
210                 this.artifactName = artifactName;
211             }
212           }
213           else {
214             this.artifactName = artifactName;
215           }
216
217         }
218       }
219     }
220     let self = this;
221     this.templateEditor = self.templateeditor.getEditor();
222     this.templateeditor.getEditor().commands.addCommand({
223       name: 'annotateCommandAlternate',
224       bindKey: { win: 'CTRL-4', mac: 'Command-4' },
225       exec: (editor: any) => {
226         this.handleAnnotation(this.modal);
227       }
228     });
229     this.templateeditor.getEditor().$enableBlockSelect = false;
230     this.templateeditor.getEditor().$enableMultiselect = false;
231     if (this.mappingEditorService.fromScreen === 'MappingScreen') {
232       this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
233       this.fileType = sessionStorage.getItem('fileType');
234     }
235     if (this.configMappingEditorContent) {
236       this.artifactRequest.templateContent = this.configMappingEditorContent;
237       this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
238     }
239     if (this.refObj) {
240       if (this.mappingEditorService.getTemplateMappingDataFromStore() && this.mappingEditorService.getTemplateMappingDataFromStore() != undefined) {
241         this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
242       }
243       else {
244         if (this.artifactName) this.retrieveTemplateFromAppc();
245       }
246     }
247     else {
248       this.Actions = [];
249       this.enableBrowse = false;
250       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
251     }
252   }
253
254   //========================== End of ngAfterViewInit() Method============================================
255   browseOption() {
256     $("#inputFile").trigger('click');
257   }
258   //========================== End of browseOption() Method============================================
259   //save to GUI
260   public saveTemplate() {
261     this.saveToGuiCacheFlag = 'true';
262     this.mappingEditorService.paramData = [];
263     if (this.configMappingEditorContent) {
264       this.initialData = this.configMappingEditorContent;
265       this.mappingEditorService.refreshEditor();
266       let paramArr: any = []
267       if (this.mappingEditorService.paramData && this.mappingEditorService.paramData != undefined) {
268         if (this.mappingEditorService.paramData.length === 0 && this.mappingEditorService.hasErrorCode === true) {
269           this.nService.error("Error", 'Special characters error', 'Error')
270           return;
271         }
272         else {
273           this.showError = false;
274         }
275       }
276       this.showTemplateVersionDiv = true;
277
278       if (this.mappingEditorService.fromScreen === 'MappingScreen') {
279         this.mappingEditorService.setTemplateMappingDataFromStore(this.configMappingEditorContent);
280       }
281       if (this.fileType === 'text/xml') {
282         sessionStorage.setItem('fileType', 'text/xml');
283       }
284       if (this.fileType === '') {
285         sessionStorage.setItem('fileType', '');
286       }
287     }
288   }
289   //========================== End of saveTemplate() Method============================================
290   retrieveTemplateFromAppc() {
291     let refObj = this.refObj;
292     if (refObj && refObj != undefined) {
293
294       let fileName = this.artifactName;
295       let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
296       let input = {
297         "input": {
298           "design-request": {
299             "request-id": this.apiToken,
300             "action": "getArtifact",
301             "payload": payload
302           }
303         }
304       };
305       let artifactContent: any;
306       this.ngProgress.start();
307       this.httpUtil.post({
308         url: environment.getDesigns,
309         data: input
310       }).subscribe(resp => {
311         if (resp.output.status.code === '400' && resp.output.status.message === "success") {
312           this.nService.success("Success", "Template retrieved successfully from APPC");
313           this.tempRetrievalResponse = resp;
314           let result = JSON.parse(resp.output.data.block).artifactInfo[0];
315           result = result['artifact-content'];
316           if ('Generated Template' === this.selectedUploadType) {
317             this.configMappingEditorContent = result
318             this.artifactRequest.templateContent = this.configMappingEditorContent;
319             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
320             if (this.artifactRequest.templateContent) {
321               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
322             }
323           }
324           this.tempretrieveFlag = true;
325           this.fileNameForTempSave = fileName;
326           this.enableDownloadButtons = true;
327           this.initialData = result;
328           this.saveTemplate();
329         }
330         else {
331           this.nService.info("Information", "There is no template saved in APPC for the selected action!");
332         }
333         this.ngProgress.done();
334       },
335         error => this.nService.error("Error", "Error in connecting to APPC Server"));
336       setTimeout(() => {
337         this.ngProgress.done();
338       }, 3500);
339     }
340   }
341   //========================== End of retrieveTemplateFromAppc() Method============================================
342   prepareAppData() {
343     let refObj = this.refObj;
344     if (refObj && refObj != undefined) {
345       let paramsKeyValueFromEditor: JSON;
346       try {
347         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
348       }
349       catch (error) {
350         console.log("Could not parse name value pairs==" + error);
351       }
352       if (paramsKeyValueFromEditor) {
353         this.showTemplateVersionDiv = true;
354         let action = this.item.action;
355         var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
356         var fileName = '';
357         let id = this.mappingEditorService.identifier;
358         if (id) fileName = this.updateFileNameForConfigScaleOut(this.item.action, scopeName, this.templateVersionNo, id);
359         else fileName = this.updateParamFileName(this.item.action, scopeName, this.templateVersionNo);
360
361         let vnfType = this.vnfType;
362         let Json = [paramsKeyValueFromEditor];
363         let slashedPayload = this.appendSlashes(JSON.stringify(Json));
364         let newPayload =
365           {
366             "userID": this.userId,
367             "vnf-type": this.vnfType,
368             "action": action,
369             "artifact-name": fileName,
370             "artifact-type": "APPC-CONFIG",
371             "artifact-version": this.templateVersionNo,
372             "artifact-contents": slashedPayload
373           }
374         let data =
375           {
376             "input": {
377               "design-request": {
378                 "request-id": this.apiToken,
379                 "action": "uploadArtifact",
380                 "payload": JSON.stringify(newPayload)
381
382               }
383             }
384           }
385         this.appDataObject.template.nameValueData = data;
386       }
387       if (this.configMappingEditorContent) {
388         let actualContent = this.configMappingEditorContent;
389         this.mappingEditorService.generateTemplate(this.templateEditor);
390         this.showTemplateVersionDiv = true;
391         let action = this.item.action;
392         let versionandFileType: any;
393         if (this.fileType === "text/xml") {
394
395           versionandFileType = this.templateVersionNo + 'V.xml'
396         } else {
397
398           versionandFileType = this.templateVersionNo + 'V.json'
399         }
400         let fileName: any;
401         if (this.tempretrieveFlag) {
402           fileName = this.fileNameForTempSave;
403         }
404         else {
405           fileName = this.artifactName;
406         }
407         let vnfType = this.vnfType;
408         let newPayload =
409           {
410             "userID": this.userId,
411             "vnf-type": this.vnfType,
412             "action": action,
413             "artifact-name": fileName,
414             "artifact-type": "APPC-CONFIG",
415             "artifact-version": this.templateVersionNo,
416             "artifact-contents": this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
417
418           }
419         let data =
420           {
421             "input": {
422               "design-request": {
423                 "request-id": this.apiToken,
424                 "action": "uploadArtifact",
425                 "payload": JSON.stringify(newPayload)
426
427               }
428             }
429           }
430         this.appDataObject.template.templateData = data;
431         this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
432       }
433     }
434   }
435   //========================== End of prepareAppData() Method============================================
436   prepareFileName(): any {
437     let fileNameObject: any = this.mappingEditorService.latestAction;
438     this.appDataObject = this.mappingEditorService.appDataObject;
439     this.downloadDataObject = this.mappingEditorService.downloadDataObject;
440     this.referenceData = fileNameObject;
441     return fileNameObject;
442   }
443   //========================== End of prepareFileName() Method============================================
444   onDownloadParameter() {
445     let refObj = this.refObj;
446     if (refObj) {
447       let paramsKeyValueFromEditor: JSON;
448       try {
449         paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
450       }
451       catch (error) {
452         console.log("Could not parse name value pairs==" + error);
453       }
454       let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, "\t")
455       var blob = new Blob([theJSON], {
456         type: "text/json"
457       });
458       this.showTemplateVersionDiv = true;
459       let fileName: any;
460       var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
461       let id = this.mappingEditorService.identifier;
462       if (id) fileName = this.updateFileNameForConfigScaleOut(this.item.action, scopeName, this.templateVersionNo, id);
463       else fileName = this.updateParamFileName(this.item.action, scopeName, this.templateVersionNo);
464
465       this.downloadDataObject.template.nameValueData = theJSON;
466       this.downloadDataObject.template.nameValueFileName = fileName;
467     }
468     else {
469       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
470     }
471
472   }
473   //========================== End of onDownloadParameter() Method============================================
474   updateParamFileName(action: any, scopeName: any, versionNo: any) {
475     let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
476     this.downloadedParamFileName = fileName;
477     return fileName;
478   }
479   //========================== End of updateParamFileName() Method============================================
480   updateFileNameForConfigScaleOut(action: any, scopeName: any, versionNo: any, id: any) {
481     let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V_' + id + '.json';
482     this.downloadedParamFileName = fileName;
483     return fileName;
484   }
485   //========================== End of updateFileNameForConfigScaleOut() Method============================================
486   public onDownloadTemplate(artifact: string) {
487     let actualContent = this.configMappingEditorContent;
488     var textToSaveAsBlob: any;
489     var config_template_fileName: any
490     let refObj = this.refObj;
491     let versionandFileType: string;
492     if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
493       this.showTemplateVersionDiv = true;
494       if (this.fileType === "text/xml") {
495         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
496           type: "text/xml"
497         });
498         versionandFileType = this.templateVersionNo + 'V.xml'
499       }
500       if (this.fileType === "text/plain") {
501         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
502           type: "text/plain"
503         });
504         versionandFileType = this.templateVersionNo + 'V.txt'
505       }
506       if (this.fileType === "text/json") {
507         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
508           type: "text/json"
509         });
510         versionandFileType = this.templateVersionNo + 'V.json'
511       }
512       if (this.tempretrieveFlag) {
513         config_template_fileName = this.fileNameForTempSave;
514         var filextension = config_template_fileName.substring(config_template_fileName.indexOf("V") + 2, config_template_fileName.length);
515
516         textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
517           type: "text/" + filextension
518         });
519       }
520       else {
521         config_template_fileName = this.artifactName;
522       }
523       this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
524       this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
525       this.downloadDataObject.template.templateFileName = config_template_fileName;
526     }
527
528   }
529   //========================== End of onDownloadTemplate() Method============================================
530   fileChange(input) {
531
532     let self = this;
533     let refObj = this.refObj;
534     this.enableValidateTemplate = true;
535
536     if (refObj && refObj != undefined) {
537       if (input.files && input.files[0]) {
538         this.spinner.show();
539         this.myfileName = input.files[0].name;
540         this.fileName = input.files[0].name;
541         this.fileType = input.files[0].type;
542         let reader = new FileReader();
543         this.readFile(input.files[0], reader, (result) => {
544           if (this.fileType === 'text/xml') {
545             sessionStorage.setItem('fileType', 'text/xml');
546           }
547           if (this.fileName.endsWith(".json")) {
548             this.fileType = "text/json";
549             sessionStorage.setItem('fileType', 'text/json');
550           }
551           if (this.fileType === '') {
552             sessionStorage.setItem('fileType', '');
553           }
554
555
556           if ('Generated Template' === this.selectedUploadType) {
557             this.configMappingEditorContent = result
558             this.artifactRequest.templateContent = this.configMappingEditorContent;
559             this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
560             if (this.artifactRequest.templateContent) {
561               this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
562             }
563           }
564           this.enableDownloadButtons = true;
565           this.initialData = result;
566           this.saveTemplate();
567           this.templateeditor.getEditor().$enableBlockSelect = false;
568           this.templateeditor.getEditor().$enableMultiselect = false;
569           setTimeout(() => {
570                         /** spinner ends after 3.5 seconds */
571                         this.spinner.hide();
572           }, 3500);
573         });
574       }
575       else {
576         this.nService.error("Error", "Failed to read file");
577       }
578       this.myInputVariable.nativeElement.value = "";
579     }
580     else {
581       this.nService.error("Error", "Please enter Action and VNF type in Reference Data screen");
582       return false;
583     }
584   }
585   //========================== End of fileChange() Method============================================
586   public readFile(file, reader, callback) {
587     // Set a callback funtion to fire after the file is fully loaded
588     reader.onload = () => {
589       // callback with the results
590       callback(reader.result);
591     }
592     this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
593     // Read the file
594     reader.readAsText(file, "UTF-8");
595   }
596   //========================== End of readFile() Method============================================
597   validateUploadedFile(fileExtension) {
598
599     if (fileExtension.toUpperCase() === 'json'.toUpperCase() || fileExtension.toUpperCase() === 'xml'.toUpperCase()) {
600       return true;
601     }
602     else {
603       return false;
604     }
605
606   }
607   //========================== End of validateUploadedFile() Method============================================
608   appendSlashes(artifactData) {
609     let x = artifactData.replace(new RegExp(',"', "g"), ',\"');
610     let y = x.replace(new RegExp('":', 'g'), '\":');
611     let z = y.replace(new RegExp('{"', 'g'), '{\"')
612     let t = z.replace(new RegExp(':"', 'g'), ':\"')
613     let m = t.replace(new RegExp('",', 'g'), '\",');
614     let n = y.replace(new RegExp('"}', 'g'), '\"}')
615     let nw = n.replace(new RegExp('{"', 'g'), '{\"');
616     let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
617     let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
618     return nw2;
619   }
620   //========================== End of appendSlashes() Method============================================
621   prepareDownloadData() {
622     this.onDownloadParameter();
623     this.onDownloadTemplate('Template');
624   }
625   //========================== End of prepareDownloadData() Method============================================
626   syncTemplate() {
627     this.mappingEditorService.replaceNamesWithBlankValues();
628     this.saveTemplate();
629
630     var templateData = this.mappingEditorService.paramData; //template data array
631     var pdData = this.paramShareService.getSessionParamData(); //PD data array
632     var paramsContent = localStorage["paramsContent"];
633
634     if (paramsContent && paramsContent != undefined) {
635       try {
636         var paramTabData = JSON.parse(paramsContent);
637       }
638       catch (error) {
639         console.log("error is : " + error)
640       }
641     }
642     var resultArr = [];
643     var json = {};
644     var resultParamObj = {};
645     let checkNamesOnlyCondition: boolean = true;
646
647     if (templateData && templateData != undefined) {
648       templateData.forEach(function (item) {
649         if (item.paramValue !== "" && item.paramValue != undefined && item.paramValue != null) {
650           checkNamesOnlyCondition = false;
651         }
652
653       });
654
655       templateData.forEach(function (item) {
656         resultParamObj[item.paramName] = item.paramValue;
657       });
658       if (paramTabData && paramTabData != undefined) {
659         templateData.forEach(function (item) {
660           for (var index in paramTabData) {
661             if (item.paramName === index) {
662               if (checkNamesOnlyCondition) {
663                 resultParamObj[index] = paramTabData[index];
664               }
665               else {
666                 if (item.paramValue === "") {
667                   resultParamObj[index] = paramTabData[index];
668                 }
669                 else {
670                   resultParamObj[index] = item.paramValue;
671                 }
672               }
673             }
674
675           }
676
677         });
678
679       }
680       localStorage["paramsContent"] = JSON.stringify(resultParamObj);
681       templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
682
683       //reformatting arr1 to match with PD
684       templateData.forEach(function (item) {
685
686         resultArr.push({
687           "name": item,
688           "type": null,
689           "description": null,
690           "required": null,
691           "default": null,
692           "source": "Manual",
693           "rule-type": null,
694           "request-keys": [{
695             "key-name": null,
696             "key-value": null
697           }, {
698             "key-name": null,
699             "key-value": null
700           }, {
701             "key-name": null,
702             "key-value": null
703           }],
704           "response-keys": [{
705             "key-name": null,
706             "key-value": null
707           }, {
708             "key-name": null,
709             "key-value": null
710           }, {
711             "key-name": null,
712             "key-value": null
713           }, {
714             "key-name": null,
715             "key-value": null
716           }, {
717             "key-name": null,
718             "key-value": null
719           }],
720           "ruleTypeValues": [null]
721
722         })
723       });
724     }
725     if (pdData && pdData != undefined) {
726       for (var i = 0; i < resultArr.length; i++) {
727
728         pdData.forEach(function (arr2item) {
729           if (resultArr[i].name === arr2item.name) {
730
731             var json = {
732               "name": arr2item.name,
733               "type": arr2item.type,
734               "description": arr2item.description,
735               "required": arr2item.required,
736               "default": arr2item.default,
737               "source": arr2item.source,
738               "rule-type": arr2item["rule-type"],
739               "request-keys": arr2item["request-keys"],
740               "response-keys": arr2item["response-keys"],
741               "ruleTypeValues": arr2item.ruleTypeValues
742             };
743             resultArr.splice(i, 1, json)
744           }
745
746         });
747
748       };
749
750     }
751     this.paramShareService.setSessionParamData(resultArr);
752     this.mappingEditorService.paramData = [];
753     //navigate to PD page after sync
754     this
755       .router
756       .navigate(['../../../vnfs/design/parameterDefinitions/create']);
757   }
758
759   //========================== End of syncTemplate() Method============================================
760   mergeParams() {
761     this.mergeStatus = this.mappingEditorService.autoAnnotateDataForParams();
762     if (this.mergeStatus) {
763       this.nService.success("Success", "Merge Successful");
764     }
765     else {
766       this.nService.error("Error", "Merge Unsuccessful");
767     }
768     this.saveTemplate();
769   }
770   //========================== End of mergeParams() Method============================================  
771   public handleAnnotation(modal) {
772
773     this.selectedWord = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
774     if (this.selectedWord && this.selectedWord != undefined) modal.open();
775   }
776   //========================== End of handleAnnotations() Method============================================ 
777   public submitNameValues() {
778     if (this.tempName) {
779       this.checkNameEntered = true;
780
781       if (this.selectedWord) {
782         if (this.selectedWord.startsWith('${(')) {
783           var replaceWord: any = this.replaceWord = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
784           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
785
786         } else {
787           let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
788           var replaceWord: any = this.replaceWord = '${(' + this.selectedWord + ')=(' + this.tempName + ')}';
789           this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
790
791         }
792       }
793       this.mappingEditorService.refreshEditor();
794       this.tempName = '';
795       this.modal.close();
796
797     }
798     else {
799       this.checkNameEntered = false;
800     }
801
802   }
803   //========================== End of submitNameValues() Method============================================
804 }