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