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