2e5d39e21f84583e5fb3bc8b92926f4a8546e027
[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 ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 ============LICENSE_END============================================
22 */
23 import * as XLSX from 'xlsx';
24 import * as _ from 'underscore';
25 import { ActivatedRoute, Router } from '@angular/router';
26 import { Component, OnInit, ViewChild } from '@angular/core';
27 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
28 import { BuildDesignComponent } from '../build-artifacts.component';
29 import { HttpUtilService } from '../../../shared/services/httpUtil/http-util.service';
30 import { Location } from '@angular/common';
31 import { MappingEditorService } from '../../..//shared/services/mapping-editor.service';
32 import { ModalComponent } from '../../../shared/modal/modal.component';
33 import { NotificationService } from '../../../shared/services/notification.service';
34 import { NotificationsService } from 'angular2-notifications';
35 import { ParamShareService } from '../../..//shared/services/paramShare.service';
36 import { environment } from '../../../../environments/environment';
37 import { saveAs } from 'file-saver';
38 import { NgProgress } from 'ngx-progressbar';
39
40
41 declare var $: any;
42 type AOA = Array<Array<any>>;
43
44 @Component({
45     selector: 'reference-dataform',
46     templateUrl: './reference-dataform.component.html',
47     styleUrls: ['./reference-dataform.component.css']
48 })
49 export class ReferenceDataformComponent implements OnInit {
50     @ViewChild(ModalComponent) modalComponent: ModalComponent;
51     public showUploadStatus: boolean = false;
52     public fileUploaded: boolean = false;
53     public uploadedData: any;
54     public statusMsg: string;
55     public uploadStatus: boolean = false;
56     public isCollapsedContent: boolean = true;
57     public vnfcCollLength: number = 0;
58     public vfncCollection = [];
59     public userForm: any;
60     public actionType: any;
61     numberTest: RegExp = /^[^.a-z]+$/;
62     public numberOfVmTest: boolean = true;
63     public tempAllData = [];
64     disableGrpNotationValue: boolean;
65     public noRefData = false;
66     public disableRetrieve = false;
67     public getRefStatus = false;
68     public uploadStatusError: boolean;
69     public showUploadErrorStatus: boolean;
70     public noData: string;
71     selectedActions = [];
72     public appData = { reference: {}, template: { templateData: {}, nameValueData: {} }, pd: {} };
73     public downloadData = {
74         reference: {},
75         template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
76         pd: { pdData: '', pdFileName: '' }
77     };
78     fileName: any;
79     public uploadFileName: any;
80     public addVmClickedFlag: boolean = false;
81     public getExcelUploadStatus: boolean = false;
82     public uploadedDataArray: any;
83     public actionFlag = false;
84     currentAction: any;
85     oldAction: any;
86     nonConfigureAction: any;
87     templateId;
88     templateIdentifier;
89     public actionLevels = [
90         'vnfc', 'vnf'
91     ];
92
93     identifierDrp: any;
94     identifierDrpValues: any = [];
95     //settings for the notifications.
96     options = {
97         timeOut: 1000,
98         showProgressBar: true,
99         pauseOnHover: true,
100         clickToClose: true,
101         maxLength: 200
102     };
103     //initializing this object to contain all the parameters to be captured
104     public referenceDataObject = {
105         action: '',
106         'action-level': 'vnf',
107         scope: { 'vnf-type': '', 'vnfc-type': '' },
108         'template': 'Y',
109         vm: [],
110         'device-protocol': '',
111         'user-name': '',
112         'port-number': '',
113         'artifact-list': []
114     };
115     public refernceScopeObj = { sourceType: '', from: '', to: '' };
116     public actions = ['', 'Configure', 'ConfigModify', 'ConfigBackup', 'ConfigRestore', 'GetRunningConfig', 'HealthCheck', 'StartApplication', 'StopApplication', 'QuiesceTraffic', 'ResumeTraffic', 'UpgradeBackout', 'UpgradeBackup', 'UpgradePostCheck', 'UpgradePreCheck', 'UpgradeSoftware', 'OpenStack Actions', 'ConfigScaleOut'];
117     public groupAnotationValue = ['', 'Pair'];
118     public groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value'];
119     public deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'NETCONF-XML', 'REST', 'CLI', 'RESTCONF'];
120     public deviceTemplates = ['', 'Y', 'N'];
121     public sourceTypeColl = ['', 'vnfType', 'vnfcType'];
122     public ipAddressBoolean = ['', 'Y', 'N'];
123     public Sample: any = {
124         'vnfc-instance': '1',
125         'vnfc-function-code': '',
126         'ipaddress-v4-oam-vip': '',
127         'group-notation-type': '',
128         'group-notation-value': ''
129     };
130     hideModal: boolean = false;
131     public self: any;
132     public uploadTypes = [{
133         value: 'Reference Data',
134         display: 'Sample Json Param File'
135     },
136     {
137         value: 'Mapping Data',
138         display: 'Sample Json Param File'
139     }
140     ];
141     public selectedUploadType: string = this.uploadTypes[0].value;
142     public vnfcTypeData: string = '';
143     public title: string;
144     public allowAction: boolean = true;
145     public actionExist: boolean = false;
146     public disableVnftype: boolean = false;
147     public otherActions: boolean = false;
148     public actionHealthCheck: boolean = false;
149     public actionChanged: boolean = false;
150     public initialAction: string = '';
151     public noCacheData: boolean;
152     public updateParams: any;
153     public vnfParams: any;
154     public firstArrayElement = [];
155     public remUploadedDataArray = [];
156     isConfigScaleOut = false
157
158     constructor(private buildDesignComponent: BuildDesignComponent, private httpUtils: HttpUtilService, private route: Router, private location: Location, private activeRoutes: ActivatedRoute, private notificationService: NotificationService,
159         private paramShareService: ParamShareService, private mappingEditorService: MappingEditorService, private modalService: NgbModal, private nService: NotificationsService, private ngProgress: NgProgress) {
160     }
161
162     ngOnInit() {
163         this.self = this;
164         let path = this.location.path;
165         this.title = 'Reference Data';
166         this.referenceDataObject = {
167             action: '',
168             'action-level': 'vnf',
169             scope: { 'vnf-type': '', 'vnfc-type': '' },
170             'template': 'Y',
171             vm: [],
172             'device-protocol': '',
173             'user-name': '',
174             'port-number': '',
175             'artifact-list': []
176         };
177         this.updateParams = sessionStorage.getItem('updateParams');
178         let cacheData = this.mappingEditorService.referenceNameObjects;
179         if (cacheData != undefined && cacheData != null && cacheData.length > 0) {
180             this.tempAllData = cacheData;
181             // console.log("latest action")
182             // console.log(this.mappingEditorService.latestAction)
183             if (this.mappingEditorService.latestAction != undefined) {
184                 this.referenceDataObject = this.mappingEditorService.latestAction;
185                 this.toggleIdentifier(this.referenceDataObject.action);
186                 //this.referenceDataObject['template-id-list'] = this.mappingEditorService.identifier
187                 //use these commented objects to be used in template and pd pages
188                 //this.templateIdentifier = this.mappingEditorService.identifier
189                 this.refernceScopeObj.sourceType = this.referenceDataObject['scopeType'];
190                 this.oldAction = this.referenceDataObject.action;
191                 this.populateExistinAction(this.referenceDataObject.action);
192             }
193         } else if (this.updateParams != 'undefined') {
194             this.getArtifact();
195         }
196         var appData = this.mappingEditorService.appDataObject;
197         if (appData != null || appData != undefined) this.appData = appData;
198         var downloadData = this.mappingEditorService.downloadDataObject;
199         if (downloadData != null || downloadData != undefined) this.downloadData = downloadData;
200         this.vnfParams = JSON.parse(sessionStorage.getItem('vnfParams'));
201         if (this.vnfParams && this.vnfParams.vnfType) {
202             this.referenceDataObject['scope']['vnf-type'] = this.vnfParams.vnfType;
203         }
204         if (this.vnfParams && this.vnfParams.vnfcType) {
205             this.referenceDataObject['scope']['vnfc-type'] = this.vnfParams.vnfcType;
206         }
207         this.uploadedDataArray = [];
208         this.remUploadedDataArray = [];
209         this.firstArrayElement = [];
210         this.uploadFileName = '';
211         this.templateIdentifier = this.mappingEditorService.identifier
212         //this.tempAllData = [];
213     }
214     toggleIdentifier(data) {
215         if (data == 'ConfigScaleOut') {
216             this.isConfigScaleOut = true
217
218         } else {
219             this.isConfigScaleOut = false
220         }
221     }
222
223     //to retrive the data from appc and assign it to the vaiables, if no data display the message reterived from the API
224     getArtifact() {
225         try {
226             let payload = JSON.parse(sessionStorage.getItem('updateParams'));
227             payload['userID'] = localStorage['userId'];
228             payload = JSON.stringify(payload);
229             let data = {
230                 'input': {
231                     'design-request': {
232                         'request-id': localStorage['apiToken'],
233                         'action': 'getArtifact',
234                         'payload': payload
235                     }
236                 }
237             };
238             this.ngProgress.start();
239             this.httpUtils.post({
240                 url: environment.getDesigns,
241                 data: data
242             }).subscribe(resp => {
243                 if (resp.output.data.block != undefined) {
244                     this.nService.success('Status', 'data fetched ');
245                     let artifactInfo = JSON.parse(resp.output.data.block).artifactInfo[0];
246                     let reference_data = JSON.parse(artifactInfo['artifact-content'])['reference_data'][0];
247                     this.referenceDataObject = reference_data;
248                     // console.log('reference data obj==' + JSON.stringify(this.referenceDataObject));
249                     this.refernceScopeObj.sourceType = this.referenceDataObject['scopeType'];
250                     this.mappingEditorService.getReferenceList().push(JSON.parse(artifactInfo['artifact-content']));
251                     this.tempAllData = JSON.parse(artifactInfo['artifact-content'])['reference_data'];
252                     this.oldAction = this.referenceDataObject.action;
253                     if (this.referenceDataObject.action === 'OpenStack Actions') {
254                         this.deviceProtocols = ['', 'OpenStack'];
255                         this.buildDesignComponent.tabs = [
256                             {
257
258                                 name: 'Reference Data',
259                                 url: 'references',
260                             }];
261                     }
262                     else {
263                         this.buildDesignComponent.tabs = [
264                             {
265                                 name: 'Reference Data',
266                                 url: 'references',
267                             }, {
268                                 name: 'Template',
269                                 url: 'templates/myTemplates',
270                             }, {
271                                 name: 'Parameter Definition',
272                                 url: 'parameterDefinitions/create'
273                             }/*, {
274                                 name: "Test",
275                                 url: 'test',
276                             }*/
277                         ];
278                     }
279                     // console.log('tempalldata===' + JSON.stringify(this.tempAllData));
280                 } else {
281                     this.nService.success('Status', 'Sorry !!! I dont have any artifact Named : ' + (JSON.parse(payload))['artifact-name']);
282                 }
283                 this.ngProgress.done();
284             });
285         }
286         catch (e) {
287             this.nService.warn('status', 'error while reteriving artifact');
288         }
289         setTimeout(() => {
290             this.ngProgress.done();
291         }, 3500);
292     }
293
294     //reinitializing the required values
295     ngOnDestroy() {
296         let referenceObject = this.prepareReferenceObject();
297         this.mappingEditorService.changeNavAppData(this.appData);
298         this.mappingEditorService.changeNavDownloadData(this.downloadData);
299         this.uploadedDataArray = [];
300         this.remUploadedDataArray = [];
301         this.firstArrayElement = [];
302         this.uploadFileName = '';
303         // this.tempAllData = [];
304         // console.log('temp all data===' + JSON.stringify(this.tempAllData));
305     }
306
307     numberValidation(event: any) {
308         // // console.log(this.numberTest.test(event));
309         if (this.numberTest.test(event) && event != 0) {
310             this.numberOfVmTest = true;
311         }
312         else {
313             this.numberOfVmTest = false;
314         }
315     }
316
317     updateSessionValues(event: any, type: string) {
318         if (type === 'action') {
319             sessionStorage.setItem('action', event);
320         }
321         if (type === 'vnfType') {
322             sessionStorage.setItem('vnfType', event);
323         }
324     }
325
326     
327     addVnfcData(vmNumber: number) {
328         var newObj = {
329             'vnfc-instance': this.referenceDataObject.vm[vmNumber].vnfc.length + 1,
330             'vnfc-type': this.vnfcTypeData,
331             'vnfc-function-code': '',
332             'ipaddress-v4-oam-vip': '',
333             'group-notation-type': '',
334             'group-notation-value': ''
335         };
336         this.referenceDataObject.vm[vmNumber].vnfc.push(newObj);
337     }
338
339     //to remove the VM's created by the user
340     removeFeature(vmNumber: any, index: any) {
341         this.referenceDataObject.vm.splice(vmNumber, 1);
342     }
343
344     //add new VM's to the configure
345     addVms() {
346         let arr = [];
347         var vnfcObj = JSON.parse(JSON.stringify(this.Sample));
348         let mberOFVm = Number(this.refernceScopeObj.from);
349         let arrlength = this.referenceDataObject.vm.length;
350         mberOFVm = arrlength + mberOFVm;
351         for (var i = (arrlength); i < mberOFVm; i++) {
352             if (this.referenceDataObject.action == 'ConfigScaleOut') {
353                 arr.push({ 'template-id': this.templateIdentifier, 'vm-instance': (i + 1), vnfc: [Object.assign({}, this.Sample)] });
354             } else {
355                 arr.push({ 'vm-instance': (i + 1), vnfc: [Object.assign({}, this.Sample)] });
356             }
357
358         }
359         //this.referenceDataObject.vm.splice(arrlength, 0, ...arr);
360         this.referenceDataObject.vm = this.referenceDataObject.vm.concat(arr); //splice(arrlength, 0, ...arr);
361     }
362
363     //Reference object to create reference data
364     prepareReferenceObject() {
365         // // console.log("this temp all data before=="+ JSON.stringify(this.tempAllData))
366
367         this.referenceDataObject['artifact-list'] = [];
368         let scopeName = '';
369         //if only vnf is there
370         if (this.referenceDataObject.scope['vnfc-type'] == '' || this.referenceDataObject.scope['vnfc-type'] == null || this.referenceDataObject.scope['vnfc-type'] == 'null') {
371             scopeName = this.referenceDataObject.scope['vnf-type'];
372             this.referenceDataObject.scope['vnfc-type'] = '';
373             this.referenceDataObject['action-level'] = 'vnf';
374             this.referenceDataObject['scopeType'] = 'vnf-type';
375         }
376         //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  
377         else {
378             scopeName = this.referenceDataObject.scope['vnfc-type'];
379             if (this.referenceDataObject.action == 'Configure' || this.referenceDataObject.action == 'ConfigModify') {
380                 this.referenceDataObject['action-level'] = 'vnfc';
381                 this.referenceDataObject['scopeType'] = 'vnfc-type';
382             } else {
383                 this.referenceDataObject['action-level'] = 'vnf';
384                 this.referenceDataObject['scopeType'] = 'vnf-type';
385             }
386         }
387         //replacing / with _ and removing spaces in the scopeName
388         if (scopeName) {
389             scopeName = scopeName.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '');
390         }
391         //marking the extension based on the device-protocol selected by the user 
392         let extension = 'json';
393         if (this.referenceDataObject['device-protocol'] == 'ANSIBLE' || this.referenceDataObject['device-protocol'] == 'CHEF' || this.referenceDataObject['device-protocol'] == 'CLI') {
394             extension = 'json';
395         } else if (this.referenceDataObject['device-protocol'] == 'NETCONF-XML' || this.referenceDataObject['device-protocol'] == 'REST') {
396             extension = 'xml';
397         }
398         //preparing the artifact list array file names along with extension
399         let config_template_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V.' + extension;
400         let pd_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V.yaml';
401         let reference_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V.json';
402
403         let configTemplate = {
404             'artifact-name': 'template_' + config_template_fileName,
405             'artifact-type': 'config_template'
406         };
407
408         let pdTemplate = {
409             'artifact-name': 'pd_' + pd_fileName,
410             'artifact-type': 'parameter_definitions'
411         };
412         if (this.referenceDataObject.action != 'ConfigScaleOut') {
413
414             this.referenceDataObject['artifact-list'].push(configTemplate,
415                 pdTemplate
416             );
417
418         } else {
419             let identifiers = this.referenceDataObject['template-id-list'];
420             if (identifiers) {
421                 for (var x = 0; x < identifiers.length; x++) {
422                     pd_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V_' + identifiers[x] + '.yaml';
423                     config_template_fileName = this.referenceDataObject.action + '_' + scopeName + '_' + '0.0.1V_' + identifiers[x] + '.' + extension;
424
425                     configTemplate = {
426                         'artifact-name': 'template_' + config_template_fileName,
427                         'artifact-type': 'config_template'
428                     };
429                     pdTemplate = {
430                         'artifact-name': 'pd_' + pd_fileName,
431                         'artifact-type': 'parameter_definitions'
432                     };
433                     this.referenceDataObject['artifact-list'].push(configTemplate,
434                         pdTemplate
435                     );
436                 }
437             }
438
439         }
440
441         if (this.referenceDataObject.scope['vnfc-type'] === '') {
442             this.referenceDataObject.scope['vnfc-type'] = '';
443         }
444         if (this.referenceDataObject.action === 'OpenStack Actions') {
445             this.referenceDataObject['template'] = 'N';
446             this.referenceDataObject['artifact-list'] = [];
447         }
448         let newObj = $.extend(true, {}, this.referenceDataObject);
449         let action = this.referenceDataObject.action;
450         let configureObject = (newObj.action == 'Configure');
451         let ConfigScaleOut = (newObj.action == 'ConfigScaleOut');
452         //delete VM's if selected action is not configure.
453         if (!ConfigScaleOut && !configureObject && this.tempAllData.length != 0) {
454             //  delete newObj.vm
455
456             if (ConfigScaleOut) {
457                 // 
458             } else {
459                 newObj.vm = [];
460             }
461             //this.tempAllData.push(newObj);
462         } else {
463             if (ConfigScaleOut) {
464
465
466                 // //add template identifier
467                 // for(let x=0;x<newObj.vm.length;x++){
468                 //     let vmObj= newObj.vm[x]
469                 //     vmObj['template-id'] = this.templateIdentifier
470                 // }
471             } else {
472                 delete newObj['template-id-list'];
473             }
474         }
475         //remove artifact list if template is N
476         if (this.referenceDataObject.template == 'N') {
477         }
478         let actionObjIndex = this.tempAllData.findIndex(obj => {
479             return obj['action'] == action;
480         });
481         if (newObj.action != 'HealthCheck') {
482             delete newObj['url'];
483         }
484         if (actionObjIndex > -1) {
485             this.tempAllData[actionObjIndex] = newObj;
486             this.mappingEditorService.saveLatestAction(this.tempAllData[actionObjIndex]);
487             this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier);
488         } else {
489             if (newObj.action != '') {
490                 this.tempAllData.push(newObj);
491                 this.mappingEditorService.saveLatestAction(newObj);
492                 this.mappingEditorService.saveLatestIdentifier(this.templateIdentifier);
493             }
494         }
495         //reset currentform vms based on action
496         if (this.currentAction == "ConfigScaleOut") {
497             //this.referenceDataObject.vm = []
498
499             let ConfigScaleOutIndex = this.tempAllData.findIndex(obj => {
500                 return obj['action'] == this.currentAction;
501             });
502             if (ConfigScaleOutIndex > -1) {
503                 this.referenceDataObject.vm = this.tempAllData[ConfigScaleOutIndex].vm
504             } else {
505                 this.referenceDataObject.vm = []
506             }
507         }
508         //Creating all action block to allow mulitple actions at once
509         let allAction = {
510             action: 'AllAction',
511             'action-level': 'vnf',
512             scope: newObj.scope,
513             'artifact-list': [{
514                 'artifact-name': 'reference_AllAction' + '_' + scopeName + '_' + '0.0.1V.json',
515                 'artifact-type': 'reference_template'
516             }]
517         };
518         let allActionIndex = this.tempAllData.findIndex(obj => {
519             return obj['action'] == 'AllAction';
520         });
521         if (allActionIndex > -1) {
522             this.tempAllData[allActionIndex] = allAction;
523         } else {
524             this.tempAllData.push(allAction);
525         }
526         // console.log('This uploaded array===' + JSON.stringify(this.uploadedDataArray));
527         if (this.uploadedDataArray && this.uploadedDataArray != undefined && this.uploadedDataArray.length != 0) {
528             /*for (var i = 0; i < this.uploadedDataArray.length; i++) {
529                 var actionData = this.uploadedDataArray[i][0];
530                // // console.log("Action data=="+ actionData);
531                 for (var j = 0; j < this.tempAllData.length; j++) {
532                     //// console.log("Actions from temp all data=="+ this.tempAllData[j].action)
533                     //// console.log("Matched=="+ (actionData === this.tempAllData[j].action))
534                     if (actionData === this.tempAllData[j].action) {
535                         this.tempAllData.splice(j,1);
536                         
537                     }
538                 }
539             }*/
540             if (this.tempAllData && this.tempAllData != undefined) {
541                 for (var i = 0; i < this.tempAllData.length; i++) {
542                     // alert(this.checkIfelementExistsInArray(this.tempAllData[i].action,this.actions))
543                     var result = false;
544
545                     if (this.tempAllData[i].action === 'AllAction') {
546                         result = true;
547                     }
548                     else {
549                         result = this.checkIfelementExistsInArray(this.tempAllData[i].action, this.actions);
550                     }
551                     if (!result) {
552                         // console.log('Removing VM action==' + this.tempAllData[i].action);
553                         this.tempAllData.splice(i, 1);
554                         i = i - 1;
555                     }
556
557                 }
558             }
559             this.addVmCapabilitiesData();
560         }
561         // // console.log("this temp all data after=="+ JSON.stringify(this.tempAllData))
562         //// console.log("temp all data from save to appc=="+JSON.stringify(this.tempAllData))
563         this.mappingEditorService.getReferenceList().push(JSON.parse(JSON.stringify(this.referenceDataObject)));
564         this.buildDesignComponent.updateAccessUpdatePages(this.referenceDataObject.action, this.mappingEditorService.getReferenceList());
565         this.mappingEditorService.changeNav(this.tempAllData);
566         return { totlaRefDtaa: this.tempAllData, scopeName: scopeName };
567     }
568
569     public checkIfelementExistsInArray(element, array) {
570         //// console.log("Element==" + element)
571         var result: boolean = false;
572
573         array.forEach(function (item) {
574             // // console.log("Item==" + item)
575             if (element === item) {
576                 // console.log('Element==' + element + 'Item==' + item);
577                 result = true;
578             }
579         }
580         );
581         return result;
582     }
583
584     upload(evt: any) {
585         /*  // console.log("This uploaded array==" + JSON.stringify(this.uploadedDataArray))
586           // // console.log("This template data before==" + JSON.stringify(this.tempAllData))
587           if (this.uploadedDataArray && this.uploadedDataArray != undefined && this.uploadedDataArray.length!=0) {
588               /*  for (var i = 0; i < this.uploadedDataArray.length; i++) {
589                     var action = this.uploadedDataArray[i][0];
590                     for (var j = 0; j < this.tempAllData.length; j++) {
591                         if (action === this.tempAllData[j].action) {
592                             this.tempAllData.splice(j);
593                             // console.log("This template data===" + this.tempAllData[j]);
594                         }
595                     }
596                 }
597                if (this.tempAllData && this.tempAllData != undefined) {
598                   for (var i = 0; i < this.tempAllData.length; i++) {
599                       // alert(this.checkIfelementExistsInArray(this.tempAllData[i].action,this.actions))
600                       var result = this.checkIfelementExistsInArray(this.tempAllData[i].action, this.actions);
601                       if (this.tempAllData[i].action === "AllAction") result = true;
602                       if (!result) {
603                           // console.log("Removing VM action==" + this.tempAllData[i].action)
604                           this.tempAllData.splice(i, 1);
605                       }
606      
607                   }
608               }
609           }
610           // // console.log("This template data after==" + JSON.stringify(this.tempAllData))
611           /* wire up file reader */
612         const target: DataTransfer = <DataTransfer>(evt.target);
613
614         //// console.log("filename========" + evt.target.files[0].name)
615         this.uploadFileName = evt.target.files[0].name;
616         var fileExtension = this.uploadFileName.substr(this.uploadFileName.lastIndexOf('.') + 1);
617         if (target.files.length != 1) {
618             throw new Error('Cannot upload multiple files on the entry');
619         }
620         if (fileExtension.toUpperCase() === 'XLS' || fileExtension.toUpperCase() === 'XLSX') {
621             const reader = new FileReader();
622             reader.onload = (e: any) => {
623                 /* read workbook */
624                 const bstr = e.target.result;
625                 //      // console.log("print 1---" + bstr);
626                 const wb = XLSX.read(bstr, { type: 'binary' });
627                 //    // console.log("print 2---" + JSON.stringify(wb));
628                 /* grab first sheet */
629                 const wsname = wb.SheetNames[0];
630                 //  // console.log("Name:---" + wsname);
631                 const ws = wb.Sheets[wsname];
632
633                 /* save data */
634
635                 let arrData = (<AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 })));
636                 //// console.log("row======" + (XLSX.utils.sheet_to_json(ws, { header: 1 })).toString())
637                 // // console.log("Array data---" + JSON.stringify(arrData));
638                 this.uploadedDataArray = arrData;
639                 this.firstArrayElement = arrData[0];
640                 var remUploadedDataArray = arrData;
641                 remUploadedDataArray.shift();
642                 this.remUploadedDataArray = remUploadedDataArray;
643                 if (arrData != null) {
644                     this.getExcelUploadStatus = true;
645                     this.nService.success('Success', 'Vm capabilities data uploaded successfully');
646
647                 }
648                 else {
649                     this.nService.success('Error', 'Empty Vm capabilities file uploaded');
650                 }
651             };
652             reader.readAsBinaryString(target.files[0]);
653             // console.log('TARGET files---' + JSON.stringify(evt.target));
654         }
655         else {
656             this.nService.error('Error', 'Incorrect VM capabilities file uploaded');
657         }
658
659     }
660
661     addVmCapabilitiesData() {
662         for (var i = 0; i < this.uploadedDataArray.length; i++) {
663             var vnfcFuncCodeArray = [];
664             var data = this.uploadedDataArray[i];
665             // // console.log("Data is "+ JSON.stringify(data))
666             //// console.log("Data length: "+ data.length)
667             for (var j = 1; j < data.length; j++) {
668                 // // console.log("Data " +j +" is "+ JSON.stringify(data[j]))
669                 if (data[j] != undefined) {
670                     if (data[j].toUpperCase() === 'Y') {
671                         vnfcFuncCodeArray.push(this.firstArrayElement[j]);
672                         //vnfcFuncCodeArray.push({name:this.firstArrayElement[j]});
673                     }
674                 }
675             }
676             var action = this.uploadedDataArray[i][0];
677             if (action && action != undefined) {
678                 var json = {
679                     'action': action,
680                     'action-level': 'vm',
681                     'scope': {
682                         'vnf-type': this.referenceDataObject['scope']['vnf-type'], //need to confirm what should be this value
683                         'vnfc-type': null
684                     },
685                     'vnfc-function-code-list': vnfcFuncCodeArray,
686                     'template': 'N',
687                     'device-protocol': 'OS'
688                 };
689
690                 this.tempAllData.push(json);
691             }
692
693         }
694     }
695
696     //download template
697     save(form: any, isValid: boolean) {
698         if (this.referenceDataObject.action === '') {
699             this.nService.error('Error', 'Select a valid Action');
700             return;
701         }
702         if (this.referenceDataObject['device-protocol'] === '') {
703             this.nService.error('Error', 'Select a valid Device protocol');
704             return;
705         }
706
707         if (isValid) {
708             let referenceObject = this.prepareReferenceObject();
709             let theJSON = JSON.stringify({ 'reference_data': this.tempAllData }, null, '\t');
710             let uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(theJSON);
711             this.downloadData.reference = theJSON;
712             this.validateTempAllData();
713             var blob = new Blob([theJSON], {
714                 type: 'text/plain'
715             });
716             let fileName = 'reference_AllAction_' + referenceObject.scopeName + '_' + '0.0.1V.json';
717             saveAs(blob, fileName);
718             var templateData = JSON.stringify(this.downloadData.template.templateData);
719             var nameValueData = JSON.stringify(this.downloadData.template.nameValueData);
720             var pdData = this.downloadData.pd.pdData;
721             if (templateData != '{}' && templateData != null && templateData != undefined) this.downloadTemplate();
722             if (nameValueData != '{}' && nameValueData != null && nameValueData != undefined) this.downloadNameValue();
723             if (pdData != '' && pdData != null && pdData != undefined) this.downloadPd();
724         }
725     }
726
727     downloadTemplate() {
728         var fileName = this.downloadData.template.templateFileName;
729         var theJSON = this.downloadData.template.templateData;
730         if (fileName != null || fileName != '') {
731             var fileExtensionArr = fileName.split('.');
732             var blob = new Blob([theJSON], {
733                 type: 'text/' + fileExtensionArr[1]
734             });
735             saveAs(blob, fileName);
736         }
737     }
738
739     downloadNameValue() {
740         var fileName = this.downloadData.template.nameValueFileName;
741         var theJSON = this.downloadData.template.nameValueData;
742         var blob = new Blob([theJSON], {
743             type: 'text/json'
744         });
745
746         saveAs(blob, fileName);
747     }
748
749     downloadPd() {
750         let fileName = this.downloadData.pd.pdFileName;
751         let theJSON = this.downloadData.pd.pdData;
752         var blob = new Blob([theJSON], {
753             type: 'text/plain'
754         });
755
756         saveAs(blob, fileName);
757     }
758
759     saveToAppc(valid, form) {
760         if (this.referenceDataObject.action === '') {
761             this.nService.error('Error', 'Select a valid Action');
762             return;
763         }
764         if (this.referenceDataObject['device-protocol'] === '') {
765             this.nService.error('Error', 'Select a valid Device protocol');
766             return;
767         }
768
769         try {
770             form._submitted = true;
771             if (valid) {
772
773                 let referenceObject = this.prepareReferenceObject();
774                 // console.log('##########');
775
776                 // console.log(referenceObject);
777                 this.validateTempAllData();
778                 let theJSON = JSON.stringify(this.tempAllData, null, '\t');
779                 let fileName = 'reference_AllAction_' + referenceObject.scopeName + '_' + '0.0.1V.json';
780                 this.uploadArtifact(JSON.stringify({ reference_data: this.tempAllData }), this.tempAllData[this.tempAllData.length - 1], fileName);
781                 var templateData = JSON.stringify(this.appData.template.templateData);
782                 var nameValueData = JSON.stringify(this.appData.template.nameValueData);
783                 var pdData = JSON.stringify(this.appData.pd);
784                 if (templateData != '{}' && templateData != null && templateData != undefined) this.saveTemp();
785                 if (nameValueData != '{}' && nameValueData != null && nameValueData != undefined) this.saveNameValue();
786                 if (pdData != '{}' && pdData != null && pdData != undefined) this.savePd();
787                 if (this.actionChanged) {
788                     this.referenceDataObject.action = this.currentAction;
789                     this.populateExistinAction(this.referenceDataObject.action);
790                     this.actionChanged = false;
791                 }
792             }
793         }
794         catch (e) {
795             this.nService.warn('status', 'unable to save the artifact');
796         }
797     }
798
799     validateTempAllData() {
800         if (this.tempAllData) {
801             var updatedData = [];
802             this.tempAllData.forEach(data => {
803                 if (data.action) {
804                     updatedData.push(data);
805                 }
806             });
807             this.tempAllData = updatedData;
808         }
809     }
810
811     appendSlashes(artifactData) {
812         return artifactData.replace(/"/g, '\\"');
813     }
814
815     uploadArtifact(artifactData, dataJson, fileName) {
816         let data = [];
817         let slashedPayload = this.appendSlashes(artifactData);
818         let newPyaload = '{"userID": "' + localStorage['userId'] + '","vnf-type" : "' + dataJson['scope']['vnf-type'] + '","action" : "AllAction","artifact-name" : "' + fileName + '","artifact-type" : "APPC-CONFIG","artifact-version" : "0.1","artifact-contents" :" ' + slashedPayload + '"}';
819         let payload = {
820             'input': {
821                 'design-request': {
822                     'request-id': localStorage['apiToken'],
823                     'action': 'uploadArtifact',
824                     'payload': newPyaload,
825                 }
826             }
827         };
828         this.ngProgress.start();
829         this.httpUtils.post({
830             url: environment.getDesigns,
831             data: payload
832         }).subscribe((resp) => {
833             if (resp != null && resp.output.status.code == '400') {
834                 window.scrollTo(0, 0);
835                 this.nService.success('Status', 'successfully uploaded the Reference Data');
836             } else {
837                 this.nService.warn('Status', 'Error while saving Reference Data');
838             }
839             this.uploadStatusError = false;
840             this.getRefStatus = false;
841             this.ngProgress.done();
842         }, (err) => {
843             this.nService.error('Status', 'Error Connecting to the APPC Network');
844             window.scrollTo(0, 0);
845         });
846         this.appData.reference = payload;
847         setTimeout(() => {
848             this.ngProgress.done();
849         }, 3500);
850     }
851
852     retriveFromAppc() {
853         if (sessionStorage.getItem('updateParams') != 'undefined') {
854             this.getArtifact();
855             this.noCacheData = false;
856         } else {
857             this.noCacheData = true;
858         }
859     }
860
861     cloneMessage(servermessage) {
862         var clone = {};
863         for (var key in servermessage) {
864             if (servermessage.hasOwnProperty(key)) //ensure not adding inherited props
865                 clone[key] = servermessage[key];
866         }
867         return clone;
868     }
869
870     public showUpload() {
871         this.selectedUploadType = this.uploadTypes[0].value;
872     };
873
874     public fileChange(input) {
875         this.fileName = input.target.files[0].name.replace(/C:\\fakepath\\/i, '');
876         this.fileUploaded = true;
877         this.disableRetrieve = true;
878         if (input.target.files && input.target.files[0]) {
879             // Create the file reader
880             let reader = new FileReader();
881             this.readFile(input.target.files[0], reader, (result) => {
882                 // After the callback fires do:
883                 if ('Reference Data' === this.selectedUploadType) {
884                     try {
885                         let obj: any;
886                         let jsonObject = (JSON.parse(result))['reference_data'];
887                         this.uploadedData = JSON.parse(JSON.stringify(jsonObject));
888                         this.tempAllData = JSON.parse(JSON.stringify(jsonObject));
889                         this.notificationService.notifySuccessMessage('Reference Data file successfully uploaded..');
890                         if (jsonObject instanceof Array) {
891                             this.referenceDataObject = jsonObject[0];
892                             jsonObject.forEach(obj => {
893                                 this.selectedActions.push(obj.action);
894                             });
895                         } else {
896                             this.referenceDataObject = jsonObject;
897                             this.selectedActions.push(jsonObject.action);
898                         }
899                         if (this.referenceDataObject.action === 'OpenStack Actions') {
900                             this.deviceProtocols = ['', 'OpenStack'];
901                             this.buildDesignComponent.tabs = [
902                                 {
903                                     type: 'dropdown',
904                                     name: 'Reference Data',
905                                     url: 'references',
906                                 }];
907                         }
908                         else {
909                             this.buildDesignComponent.tabs = [
910                                 {
911                                     name: 'Reference Data',
912                                     url: 'references',
913                                 }, {
914                                     name: 'Template',
915                                     url: 'templates/myTemplates',
916                                 }, {
917                                     name: 'Parameter Definition',
918                                     url: 'parameterDefinitions/create'
919                                 } /*, {
920         name: "Test",
921         url: 'test',
922       }*/
923                             ];
924                         }
925                         if (this.referenceDataObject.template == null) {
926                             this.referenceDataObject.template = 'Y';
927                         }
928                         if (this.referenceDataObject['action-level'] == null) {
929                             this.referenceDataObject['action-level'] = 'VNF';
930                         }
931                     } catch (e) {
932                         this.nService.error('Error', 'Incorrect file format');
933                     }
934                 }
935                 this.hideModal = true;
936             });
937         } else {
938             this.notificationService.notifyErrorMessage('Failed to read file..');
939         }
940
941     }
942
943     public readFile(file, reader, callback) {
944         // Set a callback funtion to fire after the file is fully loaded
945         reader.onload = () => {
946             // callback with the results
947             callback(reader.result);
948         };
949         this.notificationService.notifySuccessMessage('Uploading File ' + file.name + ':' + file.type + ':' + file.size);
950         // Read the file
951         reader.readAsText(file, 'UTF-8');
952     }
953
954     fileChangeEvent(fileInput: any) {
955         let obj: any = fileInput.target.files;
956     }
957
958     clearVnfcData() {
959         this.Sample = {
960             'vnfc-instance': '1',
961             'vnfc-function-code': '',
962             'ipaddress-v4-oam-vip': '',
963             'group-notation-type': '',
964             'group-notation-value': ''
965         };
966     }
967
968     setVmInstance(index) {
969         this.referenceDataObject.vm[index]['vm-instance'] = index + 1;
970     }
971
972     setVnfcType(str: String) {
973         this.Sample['vnfc-type'] = str;
974     }
975
976     getChange(value: String) {
977         if (value === 'vnfType') {
978             this.referenceDataObject.scope['vnfc-type'] = '';
979         }
980     }
981
982     resetForm() {
983         this.referenceDataObject['action-level'] = 'vnf';
984         this.referenceDataObject.template = 'Y';
985         this.referenceDataObject['device-protocol'] = '';
986         this.referenceDataObject['user-name'] = '';
987         this.referenceDataObject['port-number'] = '';
988         this.refernceScopeObj.sourceType = '';
989         this.Sample['vnfc-type'] = '';
990     }
991
992     populateExistinAction(data) {
993         let existAction = this.tempAllData.findIndex(obj => {
994             return obj.action == data;
995         });
996         if (existAction > -1) {
997             let obj = $.extend(true, {}, this.tempAllData[existAction]);
998             this.referenceDataObject = obj;
999             this.referenceDataObject.scope['vnf-type'] = obj['scope']['vnf-type'];
1000             this.referenceDataObject.scope['vnfc-type'] = obj['scope']['vnfc-type'];
1001             this.referenceDataObject['device-protocol'] = obj['device-protocol'];
1002             this.refernceScopeObj['sourceType'] = obj['scopeType'];
1003         } else {
1004             this.resetForm();
1005             this.referenceDataObject.action = data;
1006         }
1007         //# iof healthCeck change deviceprotocol drp vaues
1008         if (data == 'HealthCheck') {
1009             this.deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'REST'];
1010             this.actionHealthCheck = true;
1011         } else if (data == 'UpgradeBackout' || data == 'ResumeTraffic' || data == 'QuiesceTraffic' || data == 'UpgradeBackup' || data == 'UpgradePostCheck' || data == 'UpgradePreCheck' || data == 'UpgradeSoftware' || data == 'ConfigBackup' || data == 'ConfigRestore' || data == 'StartApplication' || data == 'StopApplication' || data == 'GetRunningConfig') {
1012             this.deviceProtocols = ['', 'CHEF', 'ANSIBLE'];
1013         } else if (data == 'OpenStack Actions') {
1014             this.deviceProtocols = ['', 'OpenStack'];
1015         } else if (data == 'ConfigScaleOut') {
1016             this.deviceProtocols = ['', 'CHEF', 'ANSIBLE', 'NETCONF'];
1017         }
1018         else {
1019             this.deviceProtocols = ['', 'ANSIBLE', 'CHEF', 'NETCONF-XML', 'RESTCONF', 'CLI'];
1020             this.actionHealthCheck = false;
1021         }
1022     }
1023
1024     //Modal pop up for action change with values entered.
1025     actionChange(data, content, userForm) {
1026         // this.actionChanged = true;
1027         this.disableGrpNotationValue = false
1028         if (data == null) {
1029             return;
1030         }
1031         if ((userForm.valid) && this.oldAction != '' && this.oldAction != undefined) {
1032             this.actionChanged = true;
1033             this.modalService.open(content).result.then(res => {
1034                 if (res == 'yes') {
1035                     this.currentAction = this.referenceDataObject.action;
1036                     this.referenceDataObject.action = this.oldAction;
1037                     $('#saveToAppc').click();//make sure the save all is done before the tempall obj is saved form the API
1038                     this.toggleIdentifier(data)
1039                     this.oldAction = this.currentAction;// this.referenceDataObject.action + '';
1040                     this.referenceDataObject.action = this.currentAction
1041
1042                     this.populateExistinAction(data);
1043                     if (this.oldAction === 'OpenStack Actions') {
1044
1045                         this.uploadedDataArray = [];
1046                         this.remUploadedDataArray = [];
1047                         this.firstArrayElement = [];
1048                         this.uploadFileName = '';
1049                         //this.tempAllData = [];
1050                     }
1051                     this.clearCache();
1052                 } else {
1053                     this.toggleIdentifier(data)
1054                     this.currentAction = this.referenceDataObject.action;
1055                     this.populateExistinAction(data);
1056                     this.oldAction = this.referenceDataObject.action + '';
1057                     this.clearCache();
1058                 }
1059             });
1060         } else {
1061             this.oldAction = this.referenceDataObject.action + '';
1062             this.populateExistinAction(data);
1063         }
1064
1065
1066         if (data == 'ConfigScaleOut') {
1067             this.groupAnotationType = ['', 'first-vnfc-name', 'fixed-value', 'relative-value', 'existing-group-name'];
1068         }
1069
1070         this.toggleIdentifier(data)
1071
1072         if (data == 'OpenStack Actions') {
1073             this.buildDesignComponent.tabs = [
1074                 {
1075                     type: 'dropdown',
1076                     name: 'Reference Data',
1077                     url: 'references',
1078                 }];
1079         }
1080         else {
1081             this.buildDesignComponent.tabs = [
1082                 {
1083                     name: 'Reference Data',
1084                     url: 'references',
1085                 }, {
1086                     name: 'Template',
1087                     url: 'templates/myTemplates',
1088                 }, {
1089                     name: 'Parameter Definition',
1090                     url: 'parameterDefinitions/create'
1091                 }/*, {
1092                     name: "Test",
1093                     url: 'test',
1094                 }*/
1095             ];
1096         }
1097         if (data == 'Configure' || data == 'ConfigModify') {
1098             this.nonConfigureAction = false;
1099         } else {
1100             this.nonConfigureAction = true;
1101         }
1102     }
1103
1104     clearCache() {
1105         // get the value and save the userid and persist it. 
1106         this.mappingEditorService.setTemplateMappingDataFromStore(undefined);
1107         localStorage['paramsContent'] = '{}';
1108         this.mappingEditorService.setParamContent(undefined);
1109         this.paramShareService.setSessionParamData(undefined);
1110         this.appData = { reference: {}, template: { templateData: {}, nameValueData: {} }, pd: {} };
1111         this.downloadData = {
1112             reference: {},
1113             template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
1114             pd: { pdData: '', pdFileName: '' }
1115         };
1116     }
1117
1118     saveTemp() {
1119         this
1120             .httpUtils
1121             .post(
1122                 { url: environment.getDesigns, data: this.appData.template.templateData })
1123             .subscribe(resp => {
1124                 if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
1125                     this.nService.success('Status', 'Successfully uploaded the Template Data');
1126                 }
1127                 if (resp.output.status.code === '401') {
1128                     this.nService.warn('Status', 'Error in saving the Template to Appc');
1129
1130                 }
1131             },
1132                 (err) => this.nService.error('Status', 'Error Connecting to the APPC Network'));
1133     }
1134
1135     saveNameValue() {
1136         this
1137             .httpUtils
1138             .post(
1139                 {
1140                     url: environment.getDesigns, data: this.appData.template.nameValueData
1141                 })
1142             .subscribe(resp => {
1143                 if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
1144                     this.nService.success('Status', 'Successfully uploaded the Name Value Pairs');
1145                 }
1146                 if (resp.output.status.code === '401') {
1147                     this.nService.warn('Status', 'Error in saving the Name value pairs to Appc');
1148                 }
1149             },
1150                 error => {
1151                     this.nService.error('Status', 'Error Connecting to the APPC Network');
1152                     return false;
1153                 });
1154     }
1155
1156     savePd() {
1157         this
1158             .httpUtils
1159             .post(
1160                 {
1161                     url: environment.getDesigns, data: this.appData.pd
1162                 })
1163             .subscribe(resp => {
1164                 if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
1165                     this.nService.success('Status', 'Successfully uploaded PD file');
1166                 }
1167                 if (resp.output.status.code === '401') {
1168                     this.nService.warn('Status', 'Error in saving the PD to Appc');
1169                 }
1170             },
1171                 error => {
1172                     this.nService.error('Status', 'Error Connecting to the APPC Network');
1173                     return false;
1174                 });
1175     }
1176
1177     openModel(toShow: any, message: any, title: any) {
1178         this.modalComponent.isShow = toShow;
1179         this.modalComponent.message = message;
1180         this.modalComponent.title = title;
1181     }
1182
1183     browseOption() {
1184         $('#inputFile').trigger('click');
1185     }
1186
1187     excelBrowseOption() {
1188         $('#excelInputFile').trigger('click');
1189     }
1190
1191     showIdentifier() {
1192         $('#identifierModal').modal();
1193     }
1194
1195     addToIdentDrp() {
1196         if (!(this.referenceDataObject['template-id-list'])) {
1197             this.referenceDataObject['template-id-list'] = [];
1198         }
1199         if(!(this.referenceDataObject['template-id-list'].indexOf(this.templateId.trim())>-1)){
1200             this.referenceDataObject['template-id-list'].push(this.templateId.trim());
1201         }
1202         
1203         // this.referenceDataObject['template-id-list'] = this.identifierDrpValues
1204         //this.identifierDrp = ""
1205     }
1206
1207     resetVms() {
1208         this.referenceDataObject.vm = [];
1209     }
1210
1211     dataModified() {
1212         this.referenceDataObject.vm = this.referenceDataObject.vm;
1213     }
1214
1215     resetGroupNotation() {
1216         if (this.Sample['group-notation-type'] == "existing-group-name") {
1217             this.Sample['group-notation-value'] = ""
1218
1219             this.disableGrpNotationValue = true
1220         } else {
1221             this.disableGrpNotationValue = false
1222         }
1223     }
1224 }