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