added ansible server functionality
[appc/cdt.git] / src / app / vnfs / build-artifacts / reference-dataform / reference-dataform.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 * as XLSX from 'xlsx';
24 import * as _ from 'underscore';
25
26 import { ActivatedRoute, Router } from '@angular/router';
27 import { Component, OnInit, ViewChild } from '@angular/core';
28 import { Observable } from 'rxjs/Observable';
29 import { BuildDesignComponent } from '../build-artifacts.component';
30 import { HttpUtilService } from '../../../shared/services/httpUtil/http-util.service';
31 import { Location } from '@angular/common';
32 import { MappingEditorService } from '../../..//shared/services/mapping-editor.service';
33 import { NgProgress } from 'ngx-progressbar';
34 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
35 import { NotificationService } from '../../../shared/services/notification.service';
36 import { NotificationsService } from 'angular2-notifications';
37 import { ParamShareService } from '../../..//shared/services/paramShare.service';
38 import { environment } from '../../../../environments/environment';
39 import { saveAs } from 'file-saver';
40 import { Jsonp } from '@angular/http';
41 import { ReferenceDataFormUtil } from './reference-dataform.util';
42 import { UtilityService } from '../../../shared/services/utilityService/utility.service';
43 import { APIService } from "../../../shared/services/cdt.apicall";
44
45 // Common Confirm Modal
46 import { DialogService } from 'ng2-bootstrap-modal';
47 import { ConfirmComponent } from "../../../shared/confirmModal/confirm.component";
48
49
50 declare var $: any;
51 type AOA = Array<Array<any>>;
52
53 @Component({
54     selector: 'reference-dataform',
55     templateUrl: './reference-dataform.component.html',
56     styleUrls: ['./reference-dataform.component.css'],
57     providers: [ReferenceDataFormUtil]
58 })
59 export class ReferenceDataformComponent implements OnInit {
60     public classNm= "ReferenceDataformComp";
61     public showUploadStatus: boolean = false;
62     public fileUploaded: boolean = false;
63     public uploadedData: any;
64     public statusMsg: string;
65     public uploadStatus: boolean = false;
66     public isCollapsedContent: boolean = true;
67     public vnfcCollLength: number = 0;
68     public vfncCollection = [];
69     public userForm: any;
70     public actionType: any;
71     numberTest: RegExp = /^[^.a-z]+$/;
72     public numberOfVmTest: boolean = true;
73     public tempAllData = [];
74     disableGrpNotationValue: boolean;
75     public noRefData = false;
76     public disableRetrieve = false;
77     public getRefStatus = false;
78     public uploadStatusError: boolean;
79     public showUploadErrorStatus: boolean;
80     public noData: string;
81     selectedActions = [];
82     public appData = { reference: {}, template: { templateData: {}, nameValueData: {} }, pd: {} };
83     public downloadData = {
84         reference: {},
85         template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
86         pd: { pdData: '', pdFileName: '' }
87     };
88     errorMessage = '';
89     invalid = true;
90     fileName: any;
91     vnfcIdentifier;
92     oldVnfcIdentifier: any
93     public uploadFileName: any;
94     public addVmClickedFlag: boolean = false;
95     public getExcelUploadStatus: boolean = false;
96     public uploadedDataArray: any;
97     public actionFlag = false;
98     currentAction: any;
99     oldAction: any;
100     nonConfigureAction: any;
101     templateId;
102     newVnfcType;
103     templateIdentifier;
104     public actionLevels = [
105         'vnfc', 'vnf'
106     ];
107     oldtemplateIdentifier: any
108     identifierDrp: any;
109     identifierDrpValues: any = [];
110     //settings for the notifications.
111     options = {
112         timeOut: 4500,
113         showProgressBar: true,
114         pauseOnHover: true,
115         clickToClose: true,
116         maxLength: 200
117     };
118     //initializing this object to contain all the parameters to be captured later
119     public referenceDataObject = {
120         action: '',
121         'action-level': 'vnf',
122         scope: { 'vnf-type': '', 'vnfc-type-list': [] },
123         'template': 'Y',
124         vm: [],
125         'device-protocol': '',
126         'user-name': '',
127         'port-number': '',
128         'artifact-list': []
129     };
130     public refernceScopeObj = { sourceType: '', from: '', to: '' };
131     public actions = ['', 'Configure', 'ConfigModify', 'ConfigBackup', 'ConfigRestore', 'GetRunningConfig', 'HealthCheck', 'StartApplication', 'StopApplication', 'QuiesceTraffic', 'ResumeTraffic', 'DistributeTraffic', 'UpgradeBackout', 'UpgradeBackup', 'UpgradePostCheck', 'UpgradePreCheck', 'UpgradeSoftware', 'OpenStack Actions', 'ConfigScaleOut'];
132     public groupAnotationValue = ['', 'Pair'];
133     public groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value'];
134     public deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'NETCONF-XML', 'REST', 'CLI', 'RESTCONF'];
135     public deviceTemplates = ['', 'Y', 'N'];
136     public sourceTypeColl = ['', 'vnfType', 'vnfcType'];
137     public ipAddressBoolean = ['', 'Y', 'N'];
138     public Sample: any = {
139         'vnfc-instance': '1',
140         'vnfc-function-code': '',
141         'ipaddress-v4-oam-vip': '',
142         'group-notation-type': '',
143         'group-notation-value': ''
144     };
145     hideModal: boolean = false;
146     public self: any;
147     public uploadTypes = [{
148         value: 'Reference Data',
149         display: 'Sample Json Param File'
150     },
151     {
152         value: 'Mapping Data',
153         display: 'Sample Json Param File'
154     }
155     ];
156     public selectedUploadType: string = this.uploadTypes[0].value;
157     public vnfcTypeData: string = '';
158     public title: string;
159     public allowAction: boolean = true;
160     public actionExist: boolean = false;
161     public disableVnftype: boolean = false;
162     public otherActions: boolean = false;
163     public actionHealthCheck: boolean = false;
164     public actionChanged: boolean = false;
165     public initialAction: string = '';
166     public noCacheData: boolean;
167     public updateParams: any;
168     public vnfParams: any;
169     public firstArrayElement = [];
170     public remUploadedDataArray = [];
171     isConfigScaleOut = false
172     isConfigOrConfigModify = false
173     configScaleOutExist: boolean
174     displayVnfc = 'false';
175     isVnfcType: boolean;
176     isVnfcTypeList: boolean = true;
177     public referencDataTab = [
178         {
179
180             name: 'Reference Data',
181             url: 'references',
182         }];
183     public allTabs = [
184         {
185             name: 'Reference Data',
186             url: 'references',
187         }, {
188             name: 'Template',
189             url: 'templates/myTemplates',
190         }, {
191             name: 'Parameter Definition',
192             url: 'parameterDefinitions/create'
193         }/*, {
194                     name: "Test",
195                     url: 'test',
196                 }*/
197     ];
198     public actionList = require('../../../../cdt.application.properties.json').Actions;
199     
200     public versionNoForApiCall = require('../../../../cdt.application.properties.json').versionNoForApiCall;
201     private displayVMBlock: boolean = true;
202
203     constructor(
204       private buildDesignComponent: BuildDesignComponent, private apiService: APIService, private utilityService: UtilityService, private httpUtils: HttpUtilService, private referenceDataFormUtil: ReferenceDataFormUtil, private route: Router, private location: Location, private activeRoutes: ActivatedRoute, private notificationService: NotificationService,
205         private paramShareService: ParamShareService, private mappingEditorService: MappingEditorService, private modalService: NgbModal, private nService: NotificationsService, private ngProgress: NgProgress,
206         private dialogService: DialogService)
207     {
208       console.log(this.classNm+
209         ": new: start: tracelvl="+this.utilityService.getTracelvl() );
210     }
211
212     ngOnInit() {
213       let methName= "ngOnInit";
214       if( this.utilityService.getTracelvl() > 0 )
215         console.log( this.classNm+": ngOnInit: start ");
216         // this.handleVMBlockDisplay();
217
218         //initializing the variables and checking for configscaleout fromm properties file
219         this.configScaleOutExist = require('../../../../cdt.application.properties.json').displayConfigScaleout;
220         this.displayVnfc = sessionStorage.getItem("vnfcSelectionFlag");
221         if (this.configScaleOutExist) {
222             this.actions = ['', 'Configure', 'ConfigModify', 'ConfigBackup', 'ConfigRestore', 'GetRunningConfig', 'HealthCheck', 'StartApplication', 'StopApplication', 'QuiesceTraffic', 'ResumeTraffic', 'DistributeTraffic', 'UpgradeBackout', 'UpgradeBackup', 'UpgradePostCheck', 'UpgradePreCheck', 'UpgradeSoftware', 'OpenStack Actions', 'ConfigScaleOut'];
223         } else {
224             this.actions = ['', 'Configure', 'ConfigModify', 'ConfigBackup', 'ConfigRestore', 'GetRunningConfig', 'HealthCheck', 'StartApplication', 'StopApplication', 'QuiesceTraffic', 'ResumeTraffic', 'DistributeTraffic', 'UpgradeBackout', 'UpgradeBackup', 'UpgradePostCheck', 'UpgradePreCheck', 'UpgradeSoftware', 'OpenStack Actions'];
225         }
226         this.self = this;
227         let path = this.location.path;
228         this.title = 'Reference Data';
229         // setting the structure for the reference data object 
230         this.referenceDataObject = {
231             action: '',
232             'action-level': 'vnf',
233             scope: { 'vnf-type': '', 'vnfc-type-list': [] },
234             'template': 'Y',
235             vm: [],
236             'device-protocol': '',
237             'user-name': '',
238             'port-number': '',
239             'artifact-list': []
240         };
241         //getting the data from session data, calling get Artifact if the data is undefined
242         this.updateParams = sessionStorage.getItem('updateParams');
243         //getting the data from the referencenameobjects if the nav is changed and assiging it to the cace data
244         let cacheData = this.mappingEditorService.referenceNameObjects;
245
246         if (this.utilityService.checkNotNull(cacheData)) {
247             //if cache data exists then assiging the data to the latest temp all data object.
248           if( this.utilityService.getTracelvl() > 0 )
249             console.log( this.classNm+": ngOnInit: have cacheData.");
250             this.tempAllData = cacheData;
251             //calling the highligted method to highlight the selected actions in the action dropdown
252             this.highlightSelectedActions(this.tempAllData)
253             // getting the latest action that the user has selected and assiging it to the reference data object once the user toggles between tabs from reference
254             if (this.mappingEditorService.latestAction != undefined) {
255                 //adding the latest action to the screen
256                 this.referenceDataObject = this.mappingEditorService.latestAction;
257                 this.toggleIdentifier(this.referenceDataObject.action);
258                 //this.referenceDataObject['template-id-list'] = this.mappingEditorService.identifier
259                 //use these commented objects to be used in template and pd pages
260                 //this.templateIdentifier = this.mappingEditorService.identifier
261                 //adding the scope from referencedata obj to referencescopeobject
262                 this.refernceScopeObj.sourceType = this.referenceDataObject['scopeType'];
263                 //assigning the latest action fetched to the old action from reference data object
264                 this.oldAction = this.referenceDataObject.action;
265                 //this method is called with the action reterived and subsequent values are assigned to refdataobj for displaying
266                 this.populateExistinAction(this.referenceDataObject.action);
267                 this.displayHideVnfc();
268             }
269         } else if (this.updateParams != 'undefined') {
270             //calls the get artifact() to reterive the values if cache data is not present
271             this.getArtifact();
272         }
273         //getting the appdata & downloadDataObject from mapping editor service and assiging it.
274         var appData = this.mappingEditorService.appDataObject;
275         if (appData != null || appData != undefined) this.appData = appData;
276         var downloadData = this.mappingEditorService.downloadDataObject;
277         if (downloadData != null || downloadData != undefined) this.downloadData = downloadData;
278
279         if (sessionStorage.getItem('vnfParams')) {
280             this.vnfParams = JSON.parse(sessionStorage.getItem('vnfParams'));
281         }
282         if (this.vnfParams && this.vnfParams.vnfType) {
283           if( this.utilityService.getTracelvl() > 0 )
284             console.log( this.classNm+": "+methName+": vnfParams.vnfType:["+
285               this.vnfParams.vnfType+"]");
286             this.referenceDataObject['scope']['vnf-type'] = this.vnfParams.vnfType;
287         }
288         if (this.vnfParams && this.vnfParams.vnfcType) {
289           if( this.utilityService.getTracelvl() > 0 )
290             console.log( this.classNm+": "+methName+": vnfParams.vnfcType:["+
291               this.vnfParams.vnfcType+"]");
292             this.referenceDataObject['scope']['vnfc-type'] = this.vnfParams.vnfcType;
293         }
294         this.uploadedDataArray = [];
295         this.remUploadedDataArray = [];
296         this.firstArrayElement = [];
297         this.uploadFileName = '';
298         this.templateIdentifier = this.mappingEditorService.identifier
299         // if (this.mappingEditorService.newObject) {
300         //     this.vnfcIdentifier = this.mappingEditorService.newObject.vnfc;
301         // }
302         // else {
303         //     this.vnfcIdentifier = '';
304         //     this.referenceDataObject['vnfcIdentifier'] = '';
305         // }
306         this.oldVnfcIdentifier = this.vnfcIdentifier;
307         if( this.utilityService.getTracelvl() > 1 )
308           console.log( this.classNm+": "+methName+": displayVnfc:["+
309             this.displayVnfc+"]");
310         if( this.utilityService.getTracelvl() > 1 )
311           console.log( this.classNm+": "+methName+": templateIdentifier:["+
312             this.templateIdentifier+"]");
313         // Enable or Block Template and PD Tabs
314         this.buildDesignComponent.getRefData(
315           { ...this.referenceDataObject, displayVnfc: this.displayVnfc },
316           { reqField: this.templateIdentifier });
317         //.. configure some drop-downs
318         this.configDrp(this.referenceDataObject.action);
319         if( this.utilityService.getTracelvl() > 0 )
320           console.log( this.classNm+": "+methName+": tempAllData:["+
321             JSON.stringify(this.tempAllData)+"]");
322         if( this.utilityService.getTracelvl() > 0 )
323           console.log( this.classNm+": "+methName+": finish.");
324     }
325
326     //setting the value to display or hide the template identifier dropdown in the screen
327     toggleIdentifier(data) {
328         if (data == 'ConfigScaleOut') {
329             this.isConfigScaleOut = true
330
331         } else {
332             this.isConfigScaleOut = false
333         }
334     }
335
336     //to retrive the data from appc and assign it to the vaiables, if no data display the message reterived from the API
337     getArtifact() {
338         if( this.utilityService.getTracelvl() > 0 )
339           console.log(this.classNm+": getArtifact: start...");
340         try {
341             // setting the isVnfcTypeList & isVnfcType to false initially
342             this.isVnfcTypeList = false;
343             this.isVnfcType = false
344             let data = this.utilityService.createPayloadForRetrieve(true, '', '', '');
345             this.ngProgress.start();
346             let serviceCall = this.apiService.callGetArtifactsApi(data);
347             serviceCall.subscribe(resp => {
348                 //getting the response and assigining it to the variables used and end the progress bar aftr the data is fetched.
349                 if (resp.output.data.block != undefined) {
350                     this.nService.success('Status', 'data fetched ');
351                     let artifactInfo = JSON.parse(resp.output.data.block).artifactInfo[0];
352                     let referenceDataAll = JSON.parse(artifactInfo['artifact-content'])['reference_data'];
353                     let reference_data = JSON.parse(artifactInfo['artifact-content'])['reference_data'][0];
354                     this.referenceDataObject = reference_data;
355                     this.toggleIdentifier(this.referenceDataObject.action);
356                     if (this.referenceDataObject.action == 'ConfigScaleOut') {
357                         this.groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value', 'existing-group-name'];
358                     }
359                     this.highlightSelectedActions(referenceDataAll)
360                     
361                     //chck vnfc or vnfcTypeList
362                     this.displayHideVnfc();
363                     
364                     // Enable or Block Template and PD Tabs
365                     this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc });
366
367                     this.refernceScopeObj.sourceType = this.referenceDataObject['scopeType'];
368                     this.mappingEditorService.getReferenceList().push(JSON.parse(artifactInfo['artifact-content']));
369                     this.tempAllData = JSON.parse(artifactInfo['artifact-content'])['reference_data'];
370                     this.oldAction = this.referenceDataObject.action;
371                     this.oldVnfcIdentifier = this.vnfcIdentifier;
372
373                     this.processReferenceDataAfterRetrieval();
374                     this.getArtifactsOpenStack();
375                 } else {
376                     this.nService.success('Status', 'Sorry !!! I dont have any artifact Named : ' + (JSON.parse(sessionStorage.getItem('updateParams')))['artifact-name']);
377                 }
378                 this.ngProgress.done();
379             });
380         }
381         catch (e) {
382             this.nService.warn('status', 'error while reteriving artifact');
383         }
384         setTimeout(() => {
385             this.ngProgress.done();
386         }, 3500);
387     }
388
389     displayHideVnfc() {
390         if( this.utilityService.getTracelvl() > 0 )
391           console.log(this.classNm+": displayHideVnfc: start...");
392         if( this.utilityService.getTracelvl() > 1 ) {
393           if( this.referenceDataObject.scope['vnfc-type-list'] ) {
394             console.log( this.classNm+
395               ": displayHideVnfc: refDataObj.scope.vnfc-type-list.length="+
396               this.referenceDataObject.scope['vnfc-type-list'].length );
397           } else {
398             console.log( this.classNm+
399               ": displayHideVnfc: refDataObj.scope.vnfc-type-list not defined");
400           };
401           console.log( this.classNm+": displayHideVnfc: scope.vnfc-type:["+
402             this.referenceDataObject.scope['vnfc-type']+"]");
403         };
404         if (this.referenceDataObject.scope['vnfc-type-list'] == undefined && (this.referenceDataObject.scope['vnfc-type'] != undefined || this.referenceDataObject.scope['vnfc-type'] != "")) {
405             this.isVnfcType = true
406             this.displayVnfc = 'true'
407             this.isVnfcTypeList = false
408         }
409         if (this.referenceDataObject.scope['vnfc-type-list'] != undefined && this.referenceDataObject.scope['vnfc-type-list'].length != 0 && (this.referenceDataObject.scope['vnfc-type'] == undefined || this.referenceDataObject.scope['vnfc-type'] == "")) {
410             this.isVnfcType = false
411             this.displayVnfc = 'true'
412             this.isVnfcTypeList = true
413             if(!this.mappingEditorService.newObject || !this.mappingEditorService.newObject.vnfc) {
414                 this.vnfcIdentifier = this.referenceDataObject.scope['vnfc-type-list'][0];
415                 // this.mappingEditorService.newObject.vnfc = this.vnfcIdentifier;
416             } else {
417                 this.vnfcIdentifier = this.mappingEditorService.newObject.vnfc;
418             }
419             this.referenceDataObject['vnfcIdentifier'] = this.vnfcIdentifier;
420             //this.vnfcChanged(this.vnfcIdentifier, FormData);
421             if( this.utilityService.getTracelvl() > 0 )
422               console.log(this.classNm+": displayHideVnfc: vnfcIdentifier:["+
423                 this.vnfcIdentifier+"]");
424         }
425         if (this.referenceDataObject.scope['vnfc-type-list'] != undefined && this.referenceDataObject.scope['vnfc-type-list'].length == 0 && this.referenceDataObject.scope['vnfc-type'] != undefined && this.referenceDataObject.scope['vnfc-type'].length == 0) {
426             if(this.displayVnfc == 'true') {
427                 this.isVnfcType = false
428                 this.displayVnfc = 'true'
429                 this.isVnfcTypeList = true
430             } else {
431                 this.isVnfcType = false
432                 this.displayVnfc = 'false'
433                 this.isVnfcTypeList = false
434             }
435         }
436         if (this.referenceDataObject.scope['vnfc-type-list'] == undefined && this.referenceDataObject.scope['vnfc-type'] == '') {
437             this.isVnfcType = false
438             this.displayVnfc = 'false'
439             this.isVnfcTypeList = false
440         }
441       if( this.utilityService.getTracelvl() > 0 )
442         console.log(this.classNm+": displayHideVnfc: finish. isVnfcType:["+
443           this.isVnfcType+" displayVnfc:["+this.displayVnfc+"] isVnfcTypeList:["+
444           this.isVnfcTypeList+"]");
445     }
446
447     //reinitializing the required values. when changing to template or pd sending the values to mapping service
448     ngOnDestroy() {
449         let referenceObject = this.prepareReferenceObject();
450         this.mappingEditorService.changeNavAppData(this.appData);
451         this.mappingEditorService.changeNavDownloadData(this.downloadData);
452         this.uploadedDataArray = [];
453         this.remUploadedDataArray = [];
454         this.firstArrayElement = [];
455         this.uploadFileName = '';
456     }
457     // vaidating the number
458     numberValidation(event: any) {
459         if (this.numberTest.test(event) && event != 0) {
460             this.numberOfVmTest = true;
461         }
462         else {
463             this.numberOfVmTest = false;
464         }
465     }
466     // update my vnf pop up session values
467     updateSessionValues(event: any, type: string) {
468       if( this.utilityService.getTracelvl() > 0 )
469         console.log(this.classNm+": updateSessionValues: type:["+type+"]");
470         if (type === 'action') {
471             sessionStorage.setItem('action', event);
472         }
473         if (type === 'vnfType') {
474             sessionStorage.setItem('vnfType', event);
475         }
476     }
477     // adding vnfc data for each vm
478     addVnfcData(vmNumber: number) {
479       if( this.utilityService.getTracelvl() > 0 )
480         console.log(this.classNm+": addVnfcData: start: vmNumber="+ vmNumber);
481         var newObj = {
482             'vnfc-instance': this.referenceDataObject.vm[vmNumber].vnfc.length + 1,
483             'vnfc-type': this.vnfcTypeData,
484             'vnfc-function-code': '',
485             'ipaddress-v4-oam-vip': '',
486             'group-notation-type': '',
487             'group-notation-value': ''
488         };
489         this.referenceDataObject.vm[vmNumber].vnfc.push(newObj);
490     }
491     //validating the vnf and vnfc data in the pop up
492     validateVnfcName(name) {
493       if( this.utilityService.getTracelvl() > 0 )
494         console.log( this.classNm+": validateVnfcName: start: name:["+name+"]");
495         if (!name.trim() || name.length < 1) {
496             this.errorMessage = '';
497             this.invalid = true;
498         } else if (name.startsWith(' ') || name.endsWith(' ')) {
499             this.errorMessage = 'Leading and trailing spaces are not allowed';
500             this.invalid = true;
501         } else if (name.includes('  ')) {
502             this.errorMessage = 'More than one space is not allowed in VNFC Type';
503             this.invalid = true;
504         } else if (name.length > 50) {
505             this.errorMessage = 'VNFC Type should be of minimum one character and maximum 50 character';
506             this.invalid = true;
507         } else {
508             this.invalid = false;
509             this.errorMessage = '';
510         }
511     }
512
513
514     //to remove the VM's created by the user
515     removeFeature(vmNumber: any, index: any, templateId) {
516         if (this.referenceDataObject.action == "Configure") {
517             this.referenceDataObject.vm.splice(vmNumber, 1);
518             this.referenceDataObject.vm.forEach((obj, arrIndex) => {
519                 if (arrIndex >= vmNumber) {
520                     obj["vm-instance"] = obj["vm-instance"] - 1
521                 }
522                 // obj["vm-instance"] = arrIndex+1
523
524             })
525         } else {
526             let data = this.referenceDataObject.vm.filter(obj => {
527                 return obj['template-id'] == templateId;
528             })
529
530             let vmIndex = this.findVmindex(data, vmNumber, templateId)
531             this.referenceDataObject.vm.splice(vmIndex, 1);
532             let index = 0
533             this.referenceDataObject.vm.forEach((obj, arrIndex) => {
534                 if (obj['template-id'] == templateId) {
535
536                     obj["vm-instance"] = index + 1
537                     index++
538                 }
539
540             })
541         }
542
543     }
544     //utility function while adding VM to check index
545     findVmindex(data, vmNumber, templateId) {
546         return this.referenceDataObject.vm.findIndex(obj => {
547             let x = obj['vm-instance'] == (vmNumber + 1) && templateId == obj['template-id']//true
548             return x
549         })
550
551     }
552
553     //add new VM's to the configure and configmodify. 
554     addVms() {
555         let arr = [];
556
557         let mberOFVm = Number(this.refernceScopeObj.from);
558         let key
559         if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
560             key = "vnfcType-id"
561         } else if (this.referenceDataObject.action == 'ConfigScaleOut') {
562             key = "template-id"
563         }
564         if (this.referenceDataObject.action == 'ConfigScaleOut' || this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
565             let existingVmsLength = this.referenceDataObject.vm.map(obj => {
566                 if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
567                     return obj["vnfcType-id"] == this.templateIdentifier
568                 } else if (this.referenceDataObject.action == 'ConfigScaleOut') {
569                     return obj["template-id"] == this.templateIdentifier
570                 }
571             }).length;
572             //mberOFVm = existingVmsLength + mberOFVm;
573             let index = 0;
574             let identifierValue
575             if (this.referenceDataObject.action == 'ConfigScaleOut') {
576                 identifierValue = this.templateIdentifier
577             } else if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify'  || this.referenceDataObject.action == 'DistributeTraffic') {
578                 identifierValue = this.vnfcIdentifier
579             }
580
581             for (var i = 0; i < mberOFVm; i++) {
582                 if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
583
584                     if (identifierValue && identifierValue != "") {
585                         this.referenceDataObject.vm.push({ 'vnfcType-id': identifierValue, 'vm-instance': (existingVmsLength + index + 1), vnfc: [Object.assign({}, this.Sample)] });
586                     } else {
587                         this.referenceDataObject.vm.push({ 'vm-instance': (existingVmsLength + index + 1), vnfc: [Object.assign({}, this.Sample)] });
588                     }
589
590                 } else if (this.referenceDataObject.action == 'ConfigScaleOut') {
591                     if (identifierValue && identifierValue != "") {
592                         this.referenceDataObject.vm.push({ 'template-id': identifierValue, 'vm-instance': (existingVmsLength + index + 1), vnfc: [Object.assign({}, this.Sample)] });
593                     }
594
595                 }
596
597                 index++;
598             }
599
600         } else {
601             let arrlength = this.referenceDataObject.vm.length;
602             mberOFVm = arrlength + mberOFVm;
603             for (var i = (arrlength); i < mberOFVm; i++) {
604                 if (this.referenceDataObject.action == 'ConfigScaleOut') {
605                     this.referenceDataObject.vm.push({ 'template-id': this.templateIdentifier, 'vm-instance': (i + 1), vnfc: [Object.assign({}, this.Sample)] });
606                 } else {
607                     this.referenceDataObject.vm.push({ 'vm-instance': (i + 1), vnfc: [Object.assign({}, this.Sample)] });
608                 }
609             }
610         }
611     }
612
613     //preparing reference obj with required business use cases
614     prepareReferenceObject(isSaving?: any) {
615       let methName= "prepareReferenceObject";
616       if( this.utilityService.getTracelvl() > 0 )
617         console.log( this.classNm+": "+methName+": start: isSaving:["+
618           isSaving+"]");
619         let scopeName = this.resetParamsOnVnfcType();
620         let extension = this.referenceDataFormUtil.decideExtension(this.referenceDataObject);
621         this.prepareArtifactList(scopeName, extension);
622
623         if (this.referenceDataObject.action === 'OpenStack Actions') {
624             this.referenceDataObject['template'] = 'N';
625             this.referenceDataObject['artifact-list'] = [];
626             this.referenceDataObject['firstRowVmSpreadSheet'] = this.firstArrayElement;
627         }
628         else{
629             this.referenceDataObject['firstRowVmSpreadSheet']=undefined;
630         }
631         //ditaching the object from the form and processing pfurther
632         let newObj = $.extend(true, {}, this.referenceDataObject);
633         let action = this.referenceDataObject.action;
634         // if (action=="ConfigScaleOut"){
635         //     this.referenceDataObject.action="true";
636         // }
637         //preparing Obj for save/download
638         newObj = this.deleteVmsforNonActions(newObj, action)
639
640         if (newObj['device-protocol'] != 'REST') {
641             delete newObj['url']
642         }
643         this.pushOrReplaceTempData(newObj, action);
644         this.addAllActionObj(newObj, scopeName);
645         this.resetTempData()
646
647
648         //rmove context url
649         //if()
650         //saving data to service
651         this.mappingEditorService.getReferenceList().push(JSON.parse(JSON.stringify(this.referenceDataObject)));
652         this.buildDesignComponent.updateAccessUpdatePages(this.referenceDataObject.action, this.mappingEditorService.getReferenceList());
653         this.mappingEditorService.changeNav(this.tempAllData);
654         //on action change or template identifier change reset the form by restting values of Reference data object
655         this.resetVmsForScaleout(this.currentAction)
656         return { totlaRefDtaa: this.tempAllData, scopeName: scopeName };
657     }
658
659     // utility function to check element existence
660     public checkIfelementExistsInArray(element, array) {
661         var result: boolean = false;
662
663         array.forEach(function (item) {
664             if (element === item) {
665                 result = true;
666             }
667         }
668         );
669         return result;
670     }
671     // when uploading the file 
672     upload(evt: any) {
673         /* wire up file reader */
674         const target: DataTransfer = <DataTransfer>(evt.target);
675         this.uploadFileName = evt.target.files[0].name;
676         var fileExtension = this.uploadFileName.substr(this.uploadFileName.lastIndexOf('.') + 1);
677         if (target.files.length != 1) {
678             throw new Error('Cannot upload multiple files on the entry');
679         }
680         if (fileExtension.toUpperCase() === 'XLS' || fileExtension.toUpperCase() === 'XLSX') {
681             const reader = new FileReader();
682             reader.onload = (e: any) => {
683                 /* read workbook */
684                 const bstr = e.target.result;
685                 const wb = XLSX.read(bstr, { type: 'binary' });
686                 /* grab first sheet */
687                 const wsname = wb.SheetNames[0];
688                 const ws = wb.Sheets[wsname];
689
690                 /* save data */
691                 this.firstArrayElement = []
692                 let arrData = (<AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 })));
693                 this.uploadedDataArray = arrData;
694                 for (var i = 0; i < arrData[0].length; i++) {
695                     this.firstArrayElement.push(arrData[0][i].replace(/[\n\r]+/g, ''))
696                 }
697                 var remUploadedDataArray = arrData;
698                 remUploadedDataArray.shift();
699                 this.remUploadedDataArray = remUploadedDataArray;
700                 if (arrData != null) {
701                     this.getExcelUploadStatus = true;
702                     this.nService.success('Success', 'Vm capabilities data uploaded successfully');
703
704                 }
705                 else {
706                     this.nService.success('Error', 'Empty Vm capabilities file uploaded');
707                 }
708             };
709             reader.readAsBinaryString(target.files[0]);
710         }
711         else {
712             this.nService.error('Error', 'Incorrect VM capabilities file uploaded');
713         }
714
715     }
716
717     addVmCapabilitiesData() {
718         for (var i = 0; i < this.uploadedDataArray.length; i++) {
719             var vnfcFuncCodeArray = [];
720             var data = this.uploadedDataArray[i];
721             for (var j = 1; j < data.length; j++) {
722                 if (data[j] != undefined) {
723                     if (data[j].toUpperCase() === 'Y') {
724                         vnfcFuncCodeArray.push(this.firstArrayElement[j]);
725                         //vnfcFuncCodeArray.push({name:this.firstArrayElement[j]});
726                     }
727                 }
728             }
729             var action = this.uploadedDataArray[i][0];
730             if (action && action != undefined) {
731                 var json = {
732                     'action': action,
733                     'action-level': 'vm',
734                     'scope': {
735                         'vnf-type': this.referenceDataObject['scope']['vnf-type'], //need to confirm what should be this value
736                         'vnfc-type-list': null
737                     },
738                     'vnfc-function-code-list': vnfcFuncCodeArray,
739                     'template': 'N',
740                     'device-protocol': 'OS'
741                 };
742
743                 this.tempAllData.push(json);
744             }
745
746         }
747     }
748
749     //download the templae pd and reference file with all the actions added.
750     save(form: any, isValid: boolean) {
751         // will show error message
752         this.showValidationErrors(this.referenceDataObject);
753
754         if (isValid) {
755             let referenceObject = this.prepareReferenceObject();
756             let removedKeysArray = []
757             this.tempAllData.forEach((data, index) => {
758                 if (data.action) {
759                     removedKeysArray.push(JSON.parse(JSON.stringify(this.deleteUnwantedKeys(data))))
760                 }
761             });
762             this.tempAllData = removedKeysArray;
763            /* var tempAllData = this.tempAllData;
764             tempAllData=this.removeParamFileNameBeforeSave(tempAllData)*/
765             
766             //tempAllData["artifact_list"]=newArtifactList;
767             let theJSON = JSON.stringify({ 'reference_data': this.tempAllData }, null, '\t');
768             let uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(theJSON);
769             this.downloadData.reference = theJSON;
770             let referenceFileName = 'reference_AllAction_' + this.referenceDataObject.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V.json';
771             this.utilityService.downloadArtifactToPc(theJSON, 'json', referenceFileName, 100);
772             this.validateTempAllData();
773             var templateData = JSON.stringify(this.downloadData.template.templateData);
774             var templateFileName = this.downloadData.template.templateFileName;
775             if (templateFileName != null || templateFileName != '') {
776                 var fileExtensionArr = templateFileName.split('.');
777             }
778             var nameValueFileName = this.downloadData.template.nameValueFileName;
779             let pdFileName = this.downloadData.pd.pdFileName;
780             var nameValueData = JSON.stringify(this.downloadData.template.nameValueData);
781             var pdData = this.downloadData.pd.pdData;
782             if (templateData != '{}' && templateData != null && templateData != undefined) this.utilityService.downloadArtifactToPc(this.downloadData.template.templateData, fileExtensionArr[1], templateFileName, 130);
783             if (nameValueData != '{}' && nameValueData != null && nameValueData != undefined) this.utilityService.downloadArtifactToPc(this.downloadData.template.nameValueData, 'json', nameValueFileName, 160);
784             if (pdData != '' && pdData != null && pdData != undefined) this.utilityService.downloadArtifactToPc(pdData, 'yaml', pdFileName, 180);
785         }
786     }
787
788   /*  removeParamFileNameBeforeSave(tempAllData)
789     {
790         var newArtifactList = [];
791             var element={};
792             for (var i = 0; i < tempAllData.length; i++) {
793                 if (this.checkIfelementExistsInArray(tempAllData[i].action,this.actions)) {
794                     var artifactList = tempAllData[i]["artifact-list"]
795                     
796                     for (var j = 0; j < artifactList.length; j++) {
797                         if (artifactList[j]["artifact-type"] != "param_values") {
798                             element = artifactList[j];
799                             newArtifactList.push(element);
800                         }
801                     }
802                     tempAllData[i]["artifact-list"] = newArtifactList
803                     newArtifactList = [];
804                     element={};
805                 }
806             }
807             return tempAllData;
808     }*/
809     // save the values to the cache, on action change without download
810     validateDataAndSaveToAppc( valid, form, event) {
811       let methName= "validateDataAndSaveToAppc";
812       if( this.utilityService.getTracelvl() > 0 )
813         console.log( this.classNm+": "+methName+": start: valid:["+valid+"]");
814         // will show error message
815         this.showValidationErrors(this.referenceDataObject);
816       if( this.utilityService.getTracelvl() > 0 )
817         console.log( this.classNm+": "+methName+": tempAllData:["+
818           JSON.stringify(this.tempAllData)+"]");
819         try {
820             form._submitted = true;
821             if (valid) {
822                 let referenceObject = this.prepareReferenceObject(true);
823                 let removedKeysArray = []
824                 this.tempAllData.forEach((data, index) => {
825                     if (data.action) {
826                         removedKeysArray.push(JSON.parse(JSON.stringify(this.deleteUnwantedKeys(data))))
827                     }
828                 });
829                 this.tempAllData = removedKeysArray;
830
831                 this.validateTempAllData();
832                 this.saveToAppc();
833                 if (this.actionChanged) {
834                     this.clearVnfcData()
835                     if (this.currentAction) {
836                         this.referenceDataObject.action = this.currentAction;
837                     }
838
839                     this.populateExistinAction(this.referenceDataObject.action);
840                     this.actionChanged = false;
841                 }
842             }
843         }
844         catch (e) {
845             this.nService.warn('status', 'unable to save the artifact');
846         }
847     }
848     //this method saves reference, template, param and PD data to APPC
849     saveToAppc() {
850       if( this.utilityService.getTracelvl() > 0 )
851         console.log( this.classNm+": saveToAppc: start: vnf-type:["+
852           this.referenceDataObject.scope['vnf-type']+"]");
853         let theJSON = JSON.stringify( this.tempAllData );
854       if( this.utilityService.getTracelvl() > 0 )
855         console.log( this.classNm+": saveToAppc: tempAllData:["+theJSON+"]");
856         let fileName = 'reference_AllAction_' + this.referenceDataObject.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V.json';
857         /*var tempAllData=this.removeParamFileNameBeforeSave(this.tempAllData);
858         this.tempAllData=tempAllData;*/
859         this.saveReferenceDataToAppc(JSON.stringify({ reference_data: this.tempAllData }), this.tempAllData[this.tempAllData.length - 1], fileName);
860
861         var templateData = JSON.stringify(this.appData.template.templateData);
862         var nameValueData = JSON.stringify(this.appData.template.nameValueData);
863         var pdData = JSON.stringify(this.appData.pd);
864         if (templateData != '{}' && templateData != null && templateData != undefined) this.referenceDataFormUtil.handleApiData(this.appData.template.templateData, 'template data');
865         if (nameValueData != '{}' && nameValueData != null && nameValueData != undefined) this.referenceDataFormUtil.handleApiData(this.appData.template.nameValueData, 'name value pairs');
866         if (pdData != '{}' && pdData != null && pdData != undefined) this.referenceDataFormUtil.handleApiData(this.appData.pd, 'PD file');
867     }
868
869     // valaidation of template data
870     validateTempAllData() {
871         if (this.tempAllData) {
872             var updatedData = [];
873             this.tempAllData.forEach(data => {
874                 if (data.action) {
875                     updatedData.push(data);
876                 }
877             });
878             this.tempAllData = updatedData;
879         }
880     }
881
882     //preparig and send the data to the API.
883     saveReferenceDataToAppc(artifactData, dataJson, fileName) {
884         let data = [];
885         let slashedPayload = this.referenceDataFormUtil.appendSlashes(artifactData);
886
887         let payload = this.utilityService.createPayLoadForSave("reference_data", dataJson['scope']['vnf-type'], "AllAction", fileName, this.versionNoForApiCall, slashedPayload);
888         this.ngProgress.start();
889         this.httpUtils.post({
890             url: environment.getDesigns,
891             data: payload
892         }).subscribe((resp) => {
893             if (resp != null && resp.output.status.code == '400') {
894                 window.scrollTo(0, 0);
895                 this.nService.success('Status', 'successfully uploaded the Reference Data');
896             } else {
897                 this.nService.warn('Status', 'Error while saving Reference Data');
898             }
899             this.uploadStatusError = false;
900             this.getRefStatus = false;
901             this.ngProgress.done();
902         }, (err) => {
903             this.nService.error('Status', 'Error Connecting to the APPC Network');
904             window.scrollTo(0, 0);
905         });
906         this.appData.reference = payload;
907         setTimeout(() => {
908             this.ngProgress.done();
909         }, 3500);
910     }
911     // if no data present in the session, fetching data from API
912     retriveFromAppc() {
913         if (sessionStorage.getItem('updateParams') != 'undefined') {
914             this.getArtifact();
915             this.noCacheData = false;
916         } else {
917             this.noCacheData = true;
918         }
919     }
920
921     public showUpload() {
922         this.selectedUploadType = this.uploadTypes[0].value;
923     };
924     // used when user uploads a file using upload file
925     public fileChange(input) {
926         this.fileName = input.target.files[0].name.replace(/C:\\fakepath\\/i, '');
927         this.fileUploaded = true;
928         this.disableRetrieve = true;
929         if (input.target.files && input.target.files[0]) {
930             // Create the file reader
931             let reader = new FileReader();
932             this.readFile(input.target.files[0], reader, (result) => {
933                 // After the callback fires do:
934                 if ('Reference Data' === this.selectedUploadType) {
935                     try {
936                         let obj: any;
937                         let jsonObject = (JSON.parse(result))['reference_data'];
938                         this.uploadedData = JSON.parse(JSON.stringify(jsonObject));
939                         //check for legacy artifact and do not allow it
940                         for (let i = 0; i < this.uploadedData.length; i++) {
941                             obj = this.uploadedData[i];
942                             if (obj.scope['vnfc-type'] != undefined && obj.scope['vnfc-type'] != '') {
943                                 this.nService.error('Error', 'The legacy reference artifact not supported');
944                                 return;
945                             }
946                         }
947
948                         this.displayVnfc = 'false';
949                         this.isVnfcType = false;
950                         this.isVnfcTypeList = false;
951                         for (let i = 0; i < this.uploadedData.length; i++) {
952                             obj = this.uploadedData[i];
953                             if (obj.scope['vnfc-type-list'] && obj.scope['vnfc-type-list'].length > 0) {
954                                 this.displayVnfc = 'true';
955                                 this.isVnfcTypeList = true;
956                                 this.vnfcIdentifier = obj.scope['vnfc-type-list'][0];
957                                 
958                             }
959                         }
960                         this.oldAction=obj.action;
961                         this.tempAllData = JSON.parse(JSON.stringify(jsonObject));
962                         //check vnfc tyoe list for old files
963                         // if (this.referenceDataObject.scope['vnfc-type-list'] == undefined) {
964                         //     this.tempAllData = []
965                         //     this.referenceDataObject = {
966                         //         action: '',
967                         //         'action-level': 'vnf',
968                         //         scope: { 'vnf-type': '', 'vnfc-type-list': [] },
969                         //         'template': 'Y',
970                         //         vm: [],
971                         //         'device-protocol': '',
972                         //         'user-name': '',
973                         //         'port-number': '',
974                         //         'artifact-list': []
975                         //     }
976                         //     this.nService.error('Error', 'Incorrect file format');
977                         //     return
978                         // }
979                         this.notificationService.notifySuccessMessage('Reference Data file successfully uploaded..');
980                         this.highlightSelectedActions(jsonObject)
981                         this.toggleIdentifier(this.referenceDataObject.action)
982                         this.populateExistinAction(this.referenceDataObject.action)
983                         this.configDrp(this.referenceDataObject.action)
984
985
986                         this.processReferenceDataAfterRetrieval();
987
988                         this.getArtifactsOpenStack();
989                         if (this.referenceDataObject.template == null) {
990                             this.referenceDataObject.template = 'Y';
991                         }
992                         if (this.referenceDataObject['action-level'] == null) {
993                             this.referenceDataObject['action-level'] = 'VNF';
994                         }
995
996                         
997                         // Enable or Block Template and PD Tabs
998                         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc });
999                     } catch (e) {
1000                         this.nService.error('Error', 'Incorrect file format');
1001                     }
1002                 }
1003                 this.hideModal = true;
1004             });
1005         } else {
1006             this.notificationService.notifyErrorMessage('Failed to read file..');
1007         }
1008
1009     }
1010
1011     // Highlights selected action on new file upload and on existing VNF 
1012     public highlightSelectedActions(jsonObject) {
1013         if (jsonObject instanceof Array) {
1014             this.referenceDataObject = jsonObject[0];
1015             jsonObject.forEach(obj => {
1016                 this.selectedActions.push(obj.action);
1017             });
1018         } else {
1019             this.referenceDataObject = jsonObject;
1020
1021             this.selectedActions.push(jsonObject.action);
1022         }
1023     }
1024
1025     public readFile(file, reader, callback) {
1026         // Set a callback funtion to fire after the file is fully loaded
1027         reader.onload = () => {
1028             // callback with the results
1029             callback(reader.result);
1030         };
1031         this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
1032         // Read the file
1033         reader.readAsText(file, 'UTF-8');
1034     }
1035
1036     fileChangeEvent(fileInput: any) {
1037         let obj: any = fileInput.target.files;
1038     }
1039     //resetting the values
1040     clearVnfcData() {
1041         this.Sample = {
1042             'vnfc-instance': '1',
1043             'vnfc-function-code': '',
1044             'ipaddress-v4-oam-vip': '',
1045             'group-notation-type': '',
1046             'group-notation-value': ''
1047         };
1048     }
1049
1050     setVmInstance(index) {
1051         this.referenceDataObject.vm[index]['vm-instance'] = index + 1;
1052     }
1053
1054     // setVnfcType(str: String) {
1055     //     this.Sample['vnfc-type'] = str;
1056     // }
1057
1058     // getChange(value: String) {
1059     //     if (value === 'vnfType') {
1060     //         this.referenceDataObject.scope['vnfc-type'] = '';
1061     //     }
1062     // }
1063     // resetting the form
1064     resetForm() {
1065         console.log( this.classNm+": resetForm: start.");
1066         this.referenceDataObject['action-level'] = 'vnf';
1067         this.referenceDataObject.template = 'Y';
1068         this.referenceDataObject['device-protocol'] = '';
1069         this.referenceDataObject['user-name'] = '';
1070         this.referenceDataObject['port-number'] = '';
1071         this.refernceScopeObj.sourceType = '';
1072         this.Sample['vnfc-type'] = '';
1073     }
1074
1075     // this method gets called with the action as parameter and the respective action details are fetched and assigned to the current page
1076     populateExistinAction(data) {
1077       let methName= "populateExistinAction";
1078       if( this.utilityService.getTracelvl() > 0 )
1079         console.log( this.classNm+": "+methName+": start: data:["+data+"]");
1080       if( this.utilityService.getTracelvl() > 0 )
1081         console.log( this.classNm+": "+methName+": tempAllData:["+
1082           JSON.stringify(this.tempAllData)+"]");
1083         let existAction = this.tempAllData.findIndex(obj => {
1084             return obj.action == data;
1085         });
1086         if (existAction > -1) {
1087             let obj = $.extend(true, {}, this.tempAllData[existAction]);
1088             this.referenceDataObject = obj;
1089             this.referenceDataObject.scope['vnf-type'] = obj['scope']['vnf-type'];
1090             this.referenceDataObject.scope['vnfc-type-list'] = obj['scope']['vnfc-type-list'];
1091             this.referenceDataObject['device-protocol'] = obj['device-protocol'];
1092             this.refernceScopeObj['sourceType'] = obj['scopeType'];
1093             if(obj['scope']['vnfc-type-list'] != undefined && obj['scope']['vnfc-type-list'].length >0) {
1094                 this.referenceDataObject['vnfcIdentifier'] = obj['scope']['vnfc-type-list'][0];
1095             }
1096         } else {
1097             console.log( this.classNm+": populateExistinAction: action not found");
1098             this.resetForm();
1099             this.referenceDataObject.action = data;
1100         }
1101         //# iof healthCeck change deviceprotocol drp vaues
1102         switch (data) {
1103             case 'HealthCheck':
1104                 this.deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'REST'];
1105                 this.actionHealthCheck = true;
1106                 break;
1107             case 'UpgradeBackout':
1108             case 'ResumeTraffic':
1109             case 'DistributeTraffic':
1110             case 'QuiesceTraffic':
1111             case 'UpgradeBackup':
1112             case 'UpgradePostCheck':
1113             case 'UpgradePreCheck':
1114             case 'UpgradeSoftware':
1115             case 'ConfigRestore':
1116             case 'StartApplication':
1117             case 'StopApplication':
1118             case 'ConfigBackup':
1119                 this.deviceProtocols = ['', 'CHEF', 'ANSIBLE'];
1120                 break;
1121             case 'OpenStack Actions':
1122                 this.deviceProtocols = ['', 'OpenStack'];
1123                 break;
1124             case 'ConfigScaleOut':
1125                 this.deviceProtocols = ['', 'CHEF', 'ANSIBLE', 'NETCONF-XML', 'RESTCONF'];
1126                 break;
1127             case 'GetRunningConfig':
1128                 this.deviceProtocols = ['', 'CHEF', 'ANSIBLE', 'NETCONF-XML', 'RESTCONF', 'CLI', 'REST'];
1129                 break;
1130             default:
1131                 this.deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'NETCONF-XML', 'RESTCONF', 'CLI'];
1132                 this.actionHealthCheck = false;
1133         }
1134     }
1135
1136     //Modal pop up for action change with values entered. 
1137     actionChange( data, userForm) {
1138       let methName= "actionChange";
1139       if( this.utilityService.getTracelvl() > 0 )
1140         console.log( this.classNm+": "+methName+": start: data:["+data+"]"+
1141           " userForm.valid:["+userForm.valid+"]");
1142       if( this.utilityService.getTracelvl() > 0 )
1143         console.log( this.classNm+": "+methName+": tempAllData:["+
1144           JSON.stringify(this.tempAllData)+"]");
1145         this.disableGrpNotationValue = false
1146         if (data == null) {
1147             console.log( this.classNm+": "+methName+": data == null");
1148             return;
1149         }
1150         if((userForm.valid) && this.oldAction != '' && this.oldAction != undefined) {
1151             this.actionChanged = true;
1152           if( this.utilityService.getTracelvl() > 0 )
1153             console.log( this.classNm+": "+methName+
1154               ": userForm valid and oldAction defined");
1155             // Calling common Confirmation Modal
1156             let disposable = this.dialogService.addDialog(ConfirmComponent)
1157                 .subscribe((isConfirmed)=>{
1158                     //We get dialog result
1159                     if(isConfirmed) {
1160                         // User clicked on Yes
1161                         this.currentAction = this.referenceDataObject.action;
1162                         this.referenceDataObject.action = this.oldAction;
1163                         $('#saveToAppc').click();//make sure the save all is done before the tempall obj is saved form the API
1164                         this.toggleIdentifier(data)
1165                         this.oldAction = this.currentAction;// this.referenceDataObject.action + '';
1166                         this.referenceDataObject.action = this.currentAction
1167
1168                         this.populateExistinAction(data);
1169                         if (this.oldAction === 'OpenStack Actions') {
1170
1171                             this.uploadedDataArray = [];
1172                             this.remUploadedDataArray = [];
1173                             this.firstArrayElement = [];
1174                             this.uploadFileName = '';
1175                             //this.tempAllData = [];
1176                         }
1177                         this.clearCache();
1178                         this.refernceScopeObj.from = '';
1179                         this.getArtifactsOpenStack();
1180
1181                         // Clears VNFC Information data on action change
1182                         this.clearVnfcData()
1183                         this.resetVmsForScaleout(data);
1184                     }
1185                     else {
1186                         // User clicked on No
1187                         this.toggleIdentifier(data)
1188                         this.currentAction = this.referenceDataObject.action;
1189                         this.populateExistinAction(data);
1190                         this.resetVmsForScaleout(data);
1191                         this.oldAction = this.referenceDataObject.action + '';
1192                         this.clearCache();
1193                         this.clearVnfcData()
1194                         this.refernceScopeObj.from = '';
1195                     }
1196
1197                     if (this.referenceDataObject.action === 'Configure' || this.referenceDataObject.action === 'ConfigModify' || this.referenceDataObject.action === 'DistributeTraffic') {
1198                         this.isConfigOrConfigModify = true;
1199                     } else {
1200                         this.isConfigOrConfigModify = false;
1201                         delete this.mappingEditorService.newObject['vnfc'];
1202                     }
1203     
1204                     // Enable or Block Template and PD Tabs
1205                     if (this.currentAction == 'ConfigScaleOut' && this.templateIdentifier && this.templateIdentifier != '') {
1206                         // let referenceDataObjectTemp = this.referenceDataObject;
1207                         // referenceDataObjectTemp['template-id'] = this.templateIdentifier;
1208                         // this.buildDesignComponent.getRefData(referenceDataObjectTemp);
1209                         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc }, { reqField: this.templateIdentifier });
1210     
1211                     } else {
1212                         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc });
1213                     }    
1214                 });
1215         } else {
1216             console.log( this.classNm+": "+methName+
1217               ": userForm Not valid or oldAction not defined");
1218             this.actionChanged = true;
1219             this.currentAction = this.referenceDataObject.action;
1220             this.oldAction = this.referenceDataObject.action + '';
1221             this.populateExistinAction(data);
1222             this.resetVmsForScaleout(data);
1223             this.toggleIdentifier(data);
1224
1225             // Enable or Block Template and PD Tabs
1226             if(this.currentAction == 'ConfigScaleOut' && this.templateIdentifier) {
1227                 // let referenceDataObjectTemp = this.referenceDataObject;
1228                 // referenceDataObjectTemp['template-id'] = this.templateIdentifier;
1229                 // this.buildDesignComponent.getRefData(referenceDataObjectTemp);
1230                 this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc }, { reqField: this.templateIdentifier });
1231             } else {
1232                 this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc });
1233             }
1234         }
1235         if( this.utilityService.getTracelvl() > 0 )
1236           console.log( this.classNm+": "+methName+": tempAllData:["+
1237             JSON.stringify(this.tempAllData)+"]");
1238         this.configDrp(data)
1239     }
1240
1241     configDrp(data) {
1242         console.log( this.classNm+": configDrp: start: data:["+data+"]");
1243         if (data == 'ConfigScaleOut') {
1244             this.groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value', 'existing-group-name'];
1245         } else {
1246             this.groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value'];
1247         }
1248         if (data == 'OpenStack Actions') {
1249             this.buildDesignComponent.tabs = this.referencDataTab;
1250         }
1251         else {
1252             this.buildDesignComponent.tabs = this.allTabs;
1253         }
1254         if (data == 'Configure' || data == 'ConfigModify' || data == 'DistributeTraffic') {
1255             this.nonConfigureAction = false;
1256         } else {
1257             this.nonConfigureAction = true;
1258         }
1259     }
1260     // removing and adding the url key based on the protocol selected
1261     deviceProtocolChange() {
1262       let methName= "deviceProtocolChange";
1263       if( this.utilityService.getTracelvl() > 0 )
1264         console.log( this.classNm+": "+methName+": start.");
1265         if (this.referenceDataObject['device-protocol'] == 'REST') {
1266
1267         } else {
1268             delete this.referenceDataObject['context-url']
1269         }
1270         // Enable or Block Template and PD Tabs
1271         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc }, {reqField: this.templateIdentifier})
1272         if( this.utilityService.getTracelvl() > 0 )
1273           console.log( this.classNm+": "+methName+": tempAllData:["+
1274             JSON.stringify(this.tempAllData)+"]");
1275     }
1276
1277     // used to call or trigger save object on template Identifier changes
1278     idChange(data, userForm) {
1279       if( this.utilityService.getTracelvl() > 0 )
1280         console.log( this.classNm+": idChange: start: data:["+data+"]");
1281         if (data == null) {
1282             return;
1283         }
1284
1285         // Enable or Block Template and PD Tabs
1286         // let referenceDataObjectTemp = this.referenceDataObject;
1287         // referenceDataObjectTemp['template-id'] = data;
1288         // this.buildDesignComponent.getRefData(referenceDataObjectTemp);
1289         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc }, { reqField: data });
1290
1291         if ((userForm.valid)) {
1292             this.currentAction = "ConfigScaleOut"
1293             this.oldtemplateIdentifier = this.templateIdentifier
1294             let referenceObject = this.prepareReferenceObject();
1295             this.actionChanged = true;
1296             if (this.templateIdentifier) {
1297                  // Calling common Confirmation Modal
1298                  let disposable = this.dialogService.addDialog(ConfirmComponent)
1299                  .subscribe((isConfirmed)=>{
1300                      //We get dialog result
1301                      if(isConfirmed) {
1302                          // User clicked on Yes
1303                          this.validateTempAllData();
1304                          this.saveToAppc();
1305                          this.clearCache();
1306                          this.clearVnfcData();
1307                          this.refernceScopeObj.from = '';
1308                      }
1309                      else {
1310                          // User clicked on No
1311                          this.clearCache();
1312                          this.refernceScopeObj.from = '';
1313                      }
1314                  });
1315             }
1316         } else {
1317             this.oldtemplateIdentifier = this.templateIdentifier
1318         }
1319
1320         // if (this.referenceDataObject.action == 'ConfigScaleOut' && data ) {
1321         //     let referenceDataObjectTemp = this.referenceDataObject;
1322         //     referenceDataObjectTemp['selectedTemplateId'] = data;
1323         //     this.buildDesignComponent.getRefData(referenceDataObjectTemp);
1324         // } else {
1325         //     this.buildDesignComponent.getRefData(this.referenceDataObject);
1326         // }
1327     }
1328
1329     // used to call or trigger save object on multiple VNFC's changes
1330     vnfcChanged( data, userForm) {
1331       if( this.utilityService.getTracelvl() > 0 )
1332         console.log( this.classNm+": vnfcChanged: new vnfcIdentifier:["+data+"]");
1333       if( this.utilityService.getTracelvl() > 1 )
1334         console.log( this.classNm+": vnfcChanged: oldVnfcIdentifier:["+
1335           this.oldVnfcIdentifier+"]");
1336       if( this.utilityService.getTracelvl() > 0 )
1337         console.log(this.classNm+": vnfcChanged:  scope.vnfc-type:["+
1338           this.referenceDataObject.scope['vnfc-type']+"]");
1339         this.vnfcIdentifier = data;
1340         //this.clearCache();
1341         if (data == null) {
1342             return;
1343         }
1344       
1345         // Enable or Block Template and PD Tabs
1346         let referenceDataObjectTemp = this.referenceDataObject;
1347         referenceDataObjectTemp['vnfcIdentifier'] = data;
1348       if( this.utilityService.getTracelvl() > 0 )
1349         console.log( this.classNm+
1350           ": vnfcChanged: displayVnfc:["+this.displayVnfc+"]");
1351         //this.buildDesignComponent.getRefData(referenceDataObjectTemp);
1352         this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc }, { reqField: data });
1353
1354       
1355         console.log( this.classNm+
1356           ": vnfcChanged: userForm.valid:["+userForm.valid+"]");
1357         if ((userForm.valid) && this.oldVnfcIdentifier != '' && this.oldVnfcIdentifier != undefined) {
1358             this.currentAction = this.referenceDataObject.action
1359             this.oldVnfcIdentifier = this.vnfcIdentifier
1360             let referenceObject = this.prepareReferenceObject();
1361             this.actionChanged = true;
1362             if (this.vnfcIdentifier) {
1363                  // Calling common Confirmation Modal
1364                  let disposable = this.dialogService.addDialog(ConfirmComponent)
1365                  .subscribe((isConfirmed)=>{
1366                      //We get dialog result
1367                      if(isConfirmed) {
1368                          // User clicked on Yes
1369                          this.validateTempAllData();
1370                          this.saveToAppc();
1371                          this.clearCache();
1372                          this.clearVnfcData()
1373                          this.refernceScopeObj.from = '';
1374                          //.. populate VNFC Type in Sample field
1375                          this.setVnfcTypeInSample( this.vnfcIdentifier );
1376                      }
1377                      else {
1378                          // User clicked on No
1379                          this.clearCache();
1380                          this.clearVnfcData()
1381                          this.refernceScopeObj.from = '';
1382                          //.. populate VNFC Type in Sample field
1383                          this.setVnfcTypeInSample( this.vnfcIdentifier );
1384                      }
1385                  });
1386             }
1387         } else {
1388             if (data != null) {
1389                 this.oldVnfcIdentifier = this.vnfcIdentifier
1390             }
1391         }
1392     }
1393
1394     clearCache()
1395     //needed for the the clearing template cache.
1396     {
1397         // get the value and save the userid and persist it.
1398         this.clearTemplateCache();
1399         this.clearPdCache();
1400         this.appData = { reference: {}, template: { templateData: {}, nameValueData: {} }, pd: {} };
1401         this.downloadData = {
1402             reference: {},
1403             template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
1404             pd: { pdData: '', pdFileName: '' }
1405         };
1406     }
1407
1408     clearTemplateCache() {
1409         this.mappingEditorService.setTemplateMappingDataFromStore(undefined);
1410         localStorage['paramsContent'] = '{}';
1411     }
1412     clearPdCache() {
1413         this.mappingEditorService.setParamContent(undefined);
1414         this.paramShareService.setSessionParamData(undefined);
1415     }
1416
1417     browseOption() {
1418         $('#inputFile').trigger('click');
1419     }
1420
1421     excelBrowseOption() {
1422         $('#excelInputFile').trigger('click');
1423     }
1424
1425     /* showIdentifier() {
1426          $('#identifierModal').modal();
1427      }
1428  
1429      showVnfcPopup() {
1430          $('#vnfcModal').modal();
1431      }*/
1432
1433     addToIdentDrp() {
1434         if (!(this.referenceDataObject['template-id-list'])) {
1435             this.referenceDataObject['template-id-list'] = [];
1436         }
1437         if (!(this.referenceDataObject['template-id-list'].indexOf(this.templateId.trim()) > -1)) {
1438             this.referenceDataObject['template-id-list'].push(this.templateId.trim());
1439         }
1440
1441         // Changing newVnfcType value to blank otherwise it will show previous value in text box of popup
1442         this.templateId = ''
1443     }
1444     // adds the vnfc to the vnfc dropdown list
1445     addVnfc() {
1446       var newVnfcTypeV= this.newVnfcType.trim();
1447       if( this.utilityService.getTracelvl() > 0 )
1448         console.log(this.classNm+
1449           ": addVnfc: start: newVnfcTypeV:["+newVnfcTypeV+"]");
1450         if (!(this.referenceDataObject.scope['vnfc-type-list'])) {
1451             this.referenceDataObject.scope['vnfc-type-list'] = [];
1452             this.vnfcIdentifier = newVnfcTypeV;
1453         } else {
1454             this.vnfcIdentifier = newVnfcTypeV;
1455         }
1456         //this.referenceDataObject['vnfcIdentifier'] = this.vnfcIdentifier;
1457         if (!(this.referenceDataObject.scope['vnfc-type-list'].indexOf(newVnfcTypeV) > -1)) {
1458             this.referenceDataObject.scope['vnfc-type-list'].push(newVnfcTypeV);
1459         }
1460         this.tempAllData.forEach(obj => {
1461             if (obj.action == "Configure" || obj.action == "ConfigModify"  || obj.action == "DistributeTraffic") {
1462                 obj.scope['vnfc-type-list'] = this.referenceDataObject.scope['vnfc-type-list']
1463             }
1464             this.resetArtifactList(obj);
1465         });
1466         //this.buildDesignComponent.getRefData({ ...this.referenceDataObject, displayVnfc: this.displayVnfc });
1467       this.setVnfcTypeInSample( newVnfcTypeV );
1468       let userForm = {valid: true};
1469       this.vnfcChanged(this.newVnfcType, userForm)
1470         // Changing newVnfcType value to blank otherwise it will show previous value in text box of popup
1471         this.newVnfcType = ''
1472     }
1473
1474     resetVms() {
1475         this.referenceDataObject.vm = [];
1476     }
1477
1478     dataModified() {
1479         //  this.referenceDataObject.vm = this.referenceDataObject.vm;
1480     }
1481     // used to show and hide the group notation value in VNFC information
1482     resetGroupNotation() {
1483         if (this.Sample['group-notation-type'] == "existing-group-name") {
1484             this.Sample['group-notation-value'] = ""
1485             this.disableGrpNotationValue = true
1486         } else {
1487             this.disableGrpNotationValue = false
1488         }
1489     }
1490
1491     resetVmsForScaleout(action) {
1492         //reset currentform vms based on action
1493         if (action == "ConfigScaleOut" || action == "Configure") {
1494             let ConfigScaleOutIndex = this.tempAllData.findIndex(obj => {
1495                 return obj['action'] == action
1496             });
1497             if (ConfigScaleOutIndex > -1) {
1498                 this.referenceDataObject.vm = this.tempAllData[ConfigScaleOutIndex].vm
1499             } else {
1500                 if (this.actionChanged) {
1501                     this.referenceDataObject.vm = []
1502                 }
1503             }
1504         }
1505     }
1506
1507     resetParamsOnVnfcType() {
1508         let scopeName: any;
1509         let vnfcTypeList = this.referenceDataObject.scope['vnfc-type-list']
1510         let vnfcType = this.referenceDataObject.scope['vnfc-type']
1511         let vnfType = this.referenceDataObject.scope['vnf-type'];
1512         //called only if only vnf is there
1513         if ((this.referenceDataFormUtil.nullCheckForVnfcTypeList(vnfcTypeList)) && (this.referenceDataFormUtil.nullCheckForVnfcType(vnfcType))
1514         ) {
1515             scopeName = vnfType;
1516             this.referenceDataObject.scope['vnfc-type'] = '';
1517             this.referenceDataObject['action-level'] = 'vnf';
1518             this.referenceDataObject['scopeType'] = 'vnf-type';
1519             scopeName = scopeName.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
1520         }
1521         //if VNFC is entered set action level & Scope type to VNFC for configure and configure modify, and default the values to vnf and vnf type for all other actions  
1522         else {
1523             if (this.referenceDataFormUtil.nullCheckForVnfcTypeList(vnfcTypeList)) {
1524                 scopeName = vnfcType ? vnfcType : "";
1525             } else {
1526                 //    scopeName = this.referenceDataObject.scope['vnfc-type-list'];
1527             }
1528
1529             if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
1530                 this.referenceDataObject['action-level'] = 'vnf';
1531                 this.referenceDataObject['scopeType'] = 'vnfc-type';
1532             } else {
1533                 this.referenceDataObject['action-level'] = 'vnf';
1534                 this.referenceDataObject['scopeType'] = 'vnf-type';
1535             }
1536         }
1537         this.referenceDataObject.scope['vnfc-type'] = this.referenceDataObject.scope['vnfc-type'] ? this.referenceDataObject.scope['vnfc-type'] : "";
1538         return scopeName
1539     }
1540
1541     //used to form the structure of the reference file
1542     prepareArtifactList(scopeName, extension) {
1543         this.referenceDataObject['artifact-list'] = [];
1544         let configTemplate
1545         let pdTemplate
1546         let paramValue
1547         let vnf = this.referenceDataObject.scope['vnf-type']
1548         if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify' || this.referenceDataObject.action == 'DistributeTraffic') {
1549             let vnfcTypeList = this.referenceDataObject.scope['vnfc-type-list'];
1550             let pd_fileName
1551             let config_template_fileName
1552
1553             let param_fileName
1554             if (vnfcTypeList && vnfcTypeList.length > 0) {
1555
1556
1557                 for (var x = 0; x < vnfcTypeList.length; x++) {
1558                     //for replacing spaces and "/" with "_"
1559                     let type = vnfcTypeList[x].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
1560                     pd_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, type, '.yaml')
1561                     config_template_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, type, extension)
1562                     param_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, type, '.json')
1563                     configTemplate = this.referenceDataFormUtil.createConfigTemplate(config_template_fileName);
1564                     pdTemplate = this.referenceDataFormUtil.createPdTemplate(pd_fileName);
1565                     paramValue = this.referenceDataFormUtil.createParamValue(param_fileName);
1566
1567                     this.referenceDataObject['artifact-list'].push(configTemplate,
1568                         pdTemplate, paramValue
1569                     );
1570                 }
1571             } else if (scopeName) {
1572                 pd_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V.yaml';
1573                 config_template_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V' + extension;
1574                 param_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V.json';
1575                 configTemplate = this.referenceDataFormUtil.createConfigTemplate(config_template_fileName);
1576                 pdTemplate = this.referenceDataFormUtil.createPdTemplate(pd_fileName);
1577                 paramValue = this.referenceDataFormUtil.createParamValue(param_fileName);
1578                 this.referenceDataObject['artifact-list'].push(configTemplate,
1579                     pdTemplate, paramValue
1580                 );
1581             }
1582
1583         } else {
1584
1585             //preparing the artifact list array file names along with extension
1586             let config_template_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, '', extension);
1587             let pd_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, '', '.yaml');
1588             let reference_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, '', '.json');
1589             let param_fileName = this.referenceDataFormUtil.createArtifactName(this.referenceDataObject.action, vnf, '', '.json');
1590             configTemplate = this.referenceDataFormUtil.createConfigTemplate(config_template_fileName);
1591             pdTemplate = this.referenceDataFormUtil.createPdTemplate(pd_fileName);
1592             paramValue = this.referenceDataFormUtil.createParamValue(param_fileName);
1593             if (this.referenceDataObject.action != 'ConfigScaleOut') {
1594
1595                 this.referenceDataObject['artifact-list'].push(configTemplate,
1596                     pdTemplate, paramValue
1597                 );
1598
1599             } else {
1600
1601                 let identifiers = this.referenceDataObject['template-id-list'];
1602                 if (identifiers) {
1603                     for (var x = 0; x < identifiers.length; x++) {
1604                         //for replacing spaces and "/" with "_"
1605                         let type = identifiers[x].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
1606                         pd_fileName = this.referenceDataFormUtil.createArtifactNameForIdentifiers(this.referenceDataObject.action, this.referenceDataObject.scope["vnf-type"], type, '.yaml');
1607                         config_template_fileName = this.referenceDataFormUtil.createArtifactNameForIdentifiers(this.referenceDataObject.action, this.referenceDataObject.scope["vnf-type"], type, extension);
1608                         param_fileName = this.referenceDataFormUtil.createArtifactNameForIdentifiers(this.referenceDataObject.action, this.referenceDataObject.scope["vnf-type"], type, '.json');
1609                         configTemplate = this.referenceDataFormUtil.createConfigTemplate(config_template_fileName);
1610                         pdTemplate = this.referenceDataFormUtil.createPdTemplate(pd_fileName);
1611                         paramValue = this.referenceDataFormUtil.createParamValue(param_fileName);
1612
1613                         this.referenceDataObject['artifact-list'].push(configTemplate,
1614                             pdTemplate, paramValue
1615                         );
1616                     }
1617                 }
1618
1619             }
1620         }
1621     }
1622     // used to remove the added vms for actions other than configure & scaleout
1623     deleteVmsforNonActions(newObj, action) {
1624         let configureObject = (action == 'Configure');
1625         let ConfigScaleOut = (action == 'ConfigScaleOut');
1626         //delete VM's if selected action is not configure.
1627         if (!ConfigScaleOut && !configureObject && this.tempAllData.length != 0) {
1628             if (ConfigScaleOut) {
1629             } else {
1630                 newObj.vm = [];
1631             }
1632         } else {
1633             if (ConfigScaleOut) {
1634             } else {
1635                 delete newObj['template-id-list'];
1636             }
1637         }
1638         return newObj
1639     }
1640     // used to replace the data in tempall obj and form the artifact names
1641     pushOrReplaceTempData(newObj, action) {
1642         let configTemplate
1643         let pdTemplate
1644         let paramValue
1645         if (newObj.action == "Configure" || newObj.action == "ConfigModify" || newObj.action == "DistributeTraffic") {
1646             let extension = this.referenceDataFormUtil.decideExtension(this.referenceDataObject);
1647             let pd_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + (newObj['vnfcIdentifier'] ? (newObj['vnfcIdentifier'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_') : "") + '0.0.1V.yaml';
1648             let config_template_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + (newObj['vnfcIdentifier'] ? (newObj['vnfcIdentifier'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_') : "") + '0.0.1V' + extension;
1649             let param_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + (newObj['vnfcIdentifier'] ? (newObj['vnfcIdentifier'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_') : "") + '0.0.1V.json';
1650             configTemplate = this.referenceDataFormUtil.createConfigTemplateForPushReplaceData(config_template_fileName);
1651             pdTemplate = this.referenceDataFormUtil.createPdTemplateForPushReplaceData(pd_fileName);
1652             paramValue = this.referenceDataFormUtil.createParamValueForPushReplaceData(param_fileName);
1653             let idValue = ""
1654             if (newObj.scope['vnfc-type']) {
1655                 idValue = newObj.scope['vnfc-type']
1656             } else if (this.vnfcIdentifier) {
1657                 idValue = this.vnfcIdentifier
1658             }
1659
1660             let arr = [configTemplate, pdTemplate, paramValue]
1661             this.mappingEditorService.selectedObj({
1662                 action: newObj.action,
1663                 vnf: newObj.scope['vnf-type'] ? newObj.scope['vnf-type'] : "",
1664                 vnfc: idValue,
1665                 protocol: newObj['device-protocol'] ? newObj['device-protocol'] : "",
1666                 param_artifact: paramValue['param_artifact'],
1667                 pd_artifact: pdTemplate['pd_artifact'],
1668                 template_artifact: configTemplate['template_artifact']
1669             });
1670         } else if (newObj.action == "ConfigScaleOut") {
1671             let extension = this.referenceDataFormUtil.decideExtension(newObj);
1672             let pd_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_0.0.1V' + '_' + (this.templateIdentifier ? (this.templateIdentifier.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '')) : "") + ".yaml";
1673             let config_template_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V_' + (this.templateIdentifier ? (this.templateIdentifier.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '') : "") + extension;
1674             let param_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V_' + (this.templateIdentifier ? (this.templateIdentifier.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '') : "") + '.json';
1675             configTemplate = this.referenceDataFormUtil.createConfigTemplateForPushReplaceData(config_template_fileName);
1676             pdTemplate = this.referenceDataFormUtil.createPdTemplateForPushReplaceData(pd_fileName);
1677             paramValue = this.referenceDataFormUtil.createParamValueForPushReplaceData(param_fileName);
1678             let arr = [configTemplate, pdTemplate, paramValue]
1679             this.mappingEditorService.selectedObj({
1680                 action: newObj.action,
1681                 vnf: newObj.scope['vnf-type'] ? newObj.scope['vnf-type'] : "",
1682                 //vnfc: newObj['vnfcIdentifier'] ? newObj['vnfcIdentifier'] : "",
1683                 protocol: newObj['device-protocol'] ? newObj['device-protocol'] : "",
1684                 templateId: this.templateIdentifier,
1685                 param_artifact: paramValue['param_artifact'],
1686                 pd_artifact: pdTemplate['pd_artifact'],
1687                 template_artifact: configTemplate['template_artifact']
1688             });
1689         }
1690         else {
1691             let extension = this.referenceDataFormUtil.decideExtension(newObj);
1692             let pd_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V.yaml';
1693             let config_template_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V' + extension;
1694             let param_fileName = this.referenceDataObject.action + '_' + newObj.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + '0.0.1V.json';
1695             configTemplate = this.referenceDataFormUtil.createConfigTemplateForPushReplaceData(config_template_fileName);
1696             pdTemplate = this.referenceDataFormUtil.createPdTemplateForPushReplaceData(pd_fileName);
1697             paramValue = this.referenceDataFormUtil.createParamValueForPushReplaceData(param_fileName);
1698             let arr = [configTemplate, pdTemplate, paramValue]
1699             this.mappingEditorService.selectedObj({
1700                 action: newObj.action,
1701                 vnf: newObj.scope['vnf-type'] ? newObj.scope['vnf-type'] : "",
1702                 protocol: newObj['device-protocol'] ? newObj['device-protocol'] : "",
1703                 param_artifact: paramValue['param_artifact'],
1704                 pd_artifact: pdTemplate['pd_artifact'],
1705                 template_artifact: configTemplate['template_artifact']
1706             });
1707         }
1708
1709         let actionObjIndex = this.tempAllData.findIndex(obj => {
1710             return obj['action'] == action;
1711         });
1712         if (actionObjIndex > -1) {
1713             this.tempAllData[actionObjIndex] = newObj;
1714             this.mappingEditorService.saveLatestAction(this.tempAllData[actionObjIndex]);
1715             if (newObj.action == "ConfigScaleOut") {
1716                 this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier);
1717             }
1718             else {
1719                 this.templateIdentifier = ('')
1720                 this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier)
1721             }
1722         } else {
1723             if (newObj.action != '') {
1724
1725                 this.tempAllData.push(newObj);
1726                 this.mappingEditorService.saveLatestAction(newObj);
1727
1728                 if (newObj.action == "ConfigScaleOut") {
1729                     this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier);
1730                 }
1731                 else {
1732                     this.templateIdentifier = ('')
1733                     this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier)
1734                 }
1735             }
1736         }
1737     }
1738     // removes the unwanted keys added in the artifact for vnfc level actions
1739     deleteUnwantedKeys(newObj) {
1740         newObj = JSON.parse(JSON.stringify(newObj))
1741         delete newObj['template-id']
1742         delete newObj['vnfcIdentifier']
1743         if (newObj.action != "ConfigScaleOut") {
1744             delete newObj['template-id-list']
1745         }
1746         if (newObj.action != 'HealthCheck') {
1747             delete newObj['url'];
1748         }
1749         if (newObj.action != "Configure" && newObj.action != "ConfigModify" && newObj.action == "DistributeTraffic") {
1750             newObj.scope['vnfc-type-list'] = [];
1751         }
1752         return newObj
1753     }
1754
1755     addAllActionObj(newObj, scopeName) {
1756
1757         //Creating all action block to allow mulitple actions at once
1758         let allAction = {
1759             action: 'AllAction',
1760             'action-level': 'vnf',
1761             scope: newObj.scope,
1762             'artifact-list': []
1763         };
1764         let vnfType = this.referenceDataObject.scope['vnf-type'].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
1765
1766         allAction['artifact-list'].push({
1767             'artifact-name': 'reference_AllAction' + '_' + vnfType + '_' + '0.0.1V.json',
1768             'artifact-type': 'reference_template'
1769         })
1770
1771         let allActionIndex = this.tempAllData.findIndex(obj => {
1772             return obj['action'] == 'AllAction';
1773         });
1774         if (allActionIndex > -1) {
1775             this.tempAllData[allActionIndex] = allAction;
1776         } else {
1777             this.tempAllData.push(allAction);
1778         }
1779     }
1780
1781     resetTempData() {
1782       let methName= "resetTempData";
1783       if( this.utilityService.getTracelvl() > 0 )
1784         console.log( this.classNm+": "+methName+": start.");
1785       if( this.utilityService.getTracelvl() > 0 )
1786         console.log( this.classNm+": "+methName+": tempAllData:["+
1787           JSON.stringify(this.tempAllData)+"]");
1788         if (this.utilityService.checkNotNull(this.uploadedDataArray)) {
1789
1790             if (this.utilityService.checkNotNull(this.tempAllData)) {
1791                 for (var i = 0; i < this.tempAllData.length; i++) {
1792                     var result = false;
1793
1794                     if (this.tempAllData[i].action === 'AllAction') {
1795                         result = true;
1796                     }
1797                     else {
1798                         result = this.checkIfelementExistsInArray(this.tempAllData[i].action, this.actions);
1799                     }
1800                     if (!result) {
1801                         this.tempAllData.splice(i, 1);
1802                         i = i - 1;
1803                     }
1804
1805                 }
1806             }
1807             this.addVmCapabilitiesData();
1808         }
1809     }
1810
1811     trackByFn(index, item) {
1812         return index; // or item.id
1813     }
1814     getArtifactsOpenStack() {
1815         var array = []
1816         var vnfcFunctionCodeArrayList = [];
1817         var vnfcSetArray = [];
1818         //  var vnfcSet = new Set();
1819         for (var i = 0; i < this.tempAllData.length; i++) {
1820             if (!this.checkIfelementExistsInArray(this.tempAllData[i].action, this.actions) && (this.tempAllData[i].action != 'AllAction')) {
1821                 var vnfcFunctionCodeArray = this.tempAllData[i]["vnfc-function-code-list"]
1822                 // vnfcSet.add("Actions")
1823                 /*  for (var j = 0; j < vnfcFunctionCodeArray.length; j++) {
1824                       vnfcSet.add(vnfcFunctionCodeArray[j])
1825                   }*/
1826                 vnfcFunctionCodeArrayList.push([this.tempAllData[i].action].concat(this.tempAllData[i]["vnfc-function-code-list"]))
1827             }
1828             if (this.tempAllData[i].action === 'OpenStack Actions') {
1829                 vnfcSetArray = this.tempAllData[i]['firstRowVmSpreadSheet']
1830             }
1831         }
1832
1833         if (vnfcSetArray) {
1834             let vnfcSetArrayLen = vnfcSetArray.length;
1835
1836             for (let i = 0; i < vnfcFunctionCodeArrayList.length; i++) {
1837                 let element = vnfcFunctionCodeArrayList[i];
1838                 for (let j = 1; j < element.length; j++) {
1839                     for (let k = j; k < vnfcSetArrayLen; k++) {
1840                         if (element[j] === vnfcSetArray[k]) {
1841                             element[j] = 'Y';
1842                         }
1843                         else {
1844                             element.splice(j, 0, '');
1845                         }
1846                         break;
1847                     }
1848                 }
1849             }
1850             this.firstArrayElement = vnfcSetArray;
1851             this.remUploadedDataArray = vnfcFunctionCodeArrayList;
1852         }
1853     }
1854
1855     // Common method to show validation errors
1856     private showValidationErrors(referenceDataObject) {
1857         if (this.referenceDataObject.action === '') {
1858             this.nService.error('Error', 'Select a valid Action');
1859             return;
1860         }
1861         if (this.referenceDataObject['device-protocol'] === '') {
1862             this.nService.error('Error', 'Select a valid Device protocol');
1863             return;
1864         }
1865
1866         if (referenceDataObject.action === 'ConfigScaleOut' && !this.templateIdentifier) {
1867             this.nService.error('Error', 'Select a valid Template Identifier');
1868         }
1869
1870         // if ((referenceDataObject.action === 'Configure' || referenceDataObject.action === 'ConfigModify') && !this.vnfcIdentifier && this.displayVnfc != 'false') {
1871         //     this.nService.error('Error', 'Select a valid Vnfc Type');
1872         //     return;
1873         // }
1874     }
1875
1876     resetArtifactList(obj) {
1877       if( this.utilityService.getTracelvl() > 0 )
1878         console.log( this.classNm+": resetArtifactList: start...");
1879         let vnfcTypeList = obj.scope['vnfc-type-list'];
1880         let vnf = this.referenceDataObject.scope['vnf-type']
1881         let pd_fileName
1882         let config_template_fileName
1883         let configTemplate
1884         let pdTemplate
1885         let paramValue
1886         let param_fileName
1887         obj['artifact-list'] = [];
1888         for (var x = 0; x < vnfcTypeList.length; x++) {
1889             let extension = this.referenceDataFormUtil.decideExtension(obj)
1890             //for replacing spaces and "/" with "_"
1891             let type = vnfcTypeList[x].replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
1892             pd_fileName = this.referenceDataObject.action + '_' + vnf.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + type + '_' + '0.0.1V.yaml';
1893             config_template_fileName = this.referenceDataObject.action + '_' + vnf.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + type + '_' + '0.0.1V' + extension;
1894             param_fileName = this.referenceDataObject.action + '_' + vnf.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '_' + type + '_' + '0.0.1V.json';
1895             configTemplate = {
1896                 'artifact-name': 'template_' + config_template_fileName,
1897                 'artifact-type': 'config_template'
1898             };
1899             pdTemplate = {
1900                 'artifact-name': 'pd_' + pd_fileName,
1901                 'artifact-type': 'parameter_definitions'
1902             };
1903             paramValue = {
1904                 'artifact-name': 'param_' + param_fileName,
1905                 'artifact-type': 'param_values'
1906             };
1907
1908             this.referenceDataObject['artifact-list'].push(configTemplate,
1909                 pdTemplate, paramValue
1910             );
1911             obj['artifact-list'].push(configTemplate,
1912                 pdTemplate, paramValue
1913             );
1914         }
1915     }
1916
1917     /**
1918      * Handles the display of VM block based on the action change
1919      */
1920     handleVMBlockDisplay() {
1921         switch (this.referenceDataObject.action) {
1922             case this.actionList.ConfigScaleOut:
1923             case this.actionList.Configure:
1924             case undefined:
1925             case '':
1926                 this.displayVMBlock = true;
1927                 break;
1928             default:
1929                 this.displayVMBlock = false;
1930         }
1931     }
1932
1933   //.. check VNFC Type equality in Upper Selection vs entered in Sample field
1934   checkVnfcTypeEqual( vnfctp: string ) {
1935     var methName= "checkVnfcTypeEqual";
1936     if( this.utilityService.getTracelvl() > 0 )
1937       console.log(this.classNm+": "+methName+": vnfctp:["+vnfctp+"]");
1938     if( this.utilityService.getTracelvl() > 0 )
1939       console.log( this.classNm+": "+methName+": vnfcIdentifier:["+
1940         this.vnfcIdentifier+"]");
1941     if( this.utilityService.getTracelvl() > 1 )
1942       console.log( this.classNm+": "+methName+":  Sample[vnfc-type]:["+
1943         this.Sample['vnfc-type']+"]");
1944     if( vnfctp != null && vnfctp.length > 0 ) {
1945       if( this.vnfcIdentifier != null && this.vnfcIdentifier.length > 0 ) {
1946         console.log(
1947           this.classNm+": "+methName+": compare non empty VNFC Types...");
1948         if( vnfctp != this.vnfcIdentifier ) {
1949           if( this.utilityService.getTracelvl() > 0 )
1950             console.log( this.classNm+": "+methName+": Non-match WARNING !");
1951           //.. display in pop-up
1952           this.nService.warn( 'WARNING',
1953             "The specified VNFC Types don't match."+
1954             " Can cause discrepancy in the artifacts.", this.options );
1955         } else {
1956           if( this.utilityService.getTracelvl() > 0 )
1957             console.log(this.classNm+": checkVnfcTypeEqual: VNFC Types're equal.");
1958         };
1959       };
1960     };
1961   };
1962
1963   //.. populating VNFC Type in Sample fields
1964   setVnfcTypeInSample( vnfctp: string ) {
1965     //clear vnfc information samples
1966       this.clearVnfcData();
1967
1968     if( this.utilityService.getTracelvl() > 0 )
1969       console.log( this.classNm+": setVnfcTypeInSample: vnfctp:["+vnfctp+"]");
1970     this.Sample['vnfc-type']= vnfctp;
1971   };
1972
1973     /**
1974      * Procesess reference data after retrieval from appc or after a reference file has been uploaded from PC.
1975     */
1976     processReferenceDataAfterRetrieval() {
1977       if( this.utilityService.getTracelvl() > 0 )
1978         console.log( this.classNm+": processReferenceDataAfterRetr: start...");
1979         if (this.referenceDataObject.action === 'OpenStack Actions') {
1980             this.deviceProtocols = ['', 'OpenStack'];
1981             this.buildDesignComponent.tabs = this.referencDataTab;
1982         } else {
1983             this.buildDesignComponent.tabs = this.allTabs;
1984         }
1985       if( this.utilityService.getTracelvl() > 1 )
1986         console.log( this.classNm+": processReferenceDataAfterRetr: done.");
1987       if( this.utilityService.getTracelvl() > 0 )
1988         console.log( this.classNm+":  vnfcIdentifier:["+this.vnfcIdentifier+"]");
1989       if( this.utilityService.getTracelvl() > 1 )
1990         console.log( this.classNm+":  oldVnfcIdentifier:["+
1991           this.oldVnfcIdentifier+"]");
1992       if( this.utilityService.getTracelvl() > 0 )
1993         console.log( this.classNm+":  refDataObj.scope.vnfc-type:["+
1994           this.referenceDataObject.scope['vnfc-type']+"]");
1995       this.setVnfcTypeInSample( this.vnfcIdentifier );
1996     }
1997
1998 }