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