d5cf56559af022aa7625c5578e3800eb6f9f0f16
[osm/NG-UI.git] / src / app / instances / ns-primitive / NSPrimitiveComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17  */
18 /**
19  * @file NS Instance Primitive Component
20  */
21 import { Component, Injector, Input, OnInit } from '@angular/core';
22 import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
23 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { NotifierService } from 'angular-notifier';
26 import { APIURLHEADER, ERRORDATA, URLPARAMS } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { KDUPRIMITIVELEVEL, NSData, VDUPRIMITIVELEVEL } from 'NSDModel';
30 import { NSPrimitiveParams } from 'NSInstanceModel';
31 import { RestService } from 'RestService';
32 import { SharedService } from 'SharedService';
33 import { isNullOrUndefined } from 'util';
34
35 /**
36  * Creating component
37  * @Component takes NSPrimitiveComponent.html as template url
38  */
39 @Component({
40     templateUrl: './NSPrimitiveComponent.html',
41     styleUrls: ['./NSPrimitiveComponent.scss']
42 })
43 /** Exporting a class @exports NSPrimitiveComponent */
44 export class NSPrimitiveComponent implements OnInit {
45     /** Form valid on submit trigger @public */
46     public submitted: boolean = false;
47
48     /** To inject services @public */
49     public injector: Injector;
50
51     /** Instance for active modal service @public */
52     public activeModal: NgbActiveModal;
53
54     /** FormGroup instance added to the form @ html @public */
55     public primitiveForm: FormGroup;
56
57     /** Primitive params array @public */
58     public primitiveParams: FormArray;
59
60     /** Variable set for twoway binding @public */
61     public nsdId: string;
62
63     /** Check the loading results @public */
64     public isLoadingResults: boolean = false;
65
66     /** Give the message for the loading @public */
67     public message: string = 'PLEASEWAIT';
68
69     /** Contains list of primitive parameter @public */
70     public primitiveParameter: {}[] = [];
71
72     /** Input contains component objects @public */
73     @Input() public params: URLPARAMS;
74
75     /** Contains list of primitive actions @public */
76     public primitiveList: {}[];
77
78     /** Contains objects that is used to hold types of primitive @public */
79     public primitiveTypeList: {}[] = [];
80
81     /** Model value used to hold selected primitive type @public */
82     public primitiveType: string;
83
84     /** Contains list of VDU primitive lists @public */
85     public vduList: {}[];
86
87     /** Contains list of KDU primitive lists @public */
88     public kduList: {}[];
89
90     /** FormBuilder instance added to the formBuilder @private */
91     private formBuilder: FormBuilder;
92
93     /** Utilizes rest service for any CRUD operations @private */
94     private restService: RestService;
95
96     /** packages data service collections @private */
97     private dataService: DataService;
98
99     /** Contains tranlsate instance @private */
100     private translateService: TranslateService;
101
102     /** Notifier service to popup notification @private */
103     private notifierService: NotifierService;
104
105     /** Contains all methods related to shared @private */
106     private sharedService: SharedService;
107
108     /** Contains objects that is used to convert key/value pair @private */
109     private objectPrimitiveParams: {} = {};
110
111     constructor(injector: Injector) {
112         this.injector = injector;
113         this.restService = this.injector.get(RestService);
114         this.dataService = this.injector.get(DataService);
115         this.translateService = this.injector.get(TranslateService);
116         this.notifierService = this.injector.get(NotifierService);
117         this.sharedService = this.injector.get(SharedService);
118         this.activeModal = this.injector.get(NgbActiveModal);
119         this.formBuilder = this.injector.get(FormBuilder);
120         this.primitiveTypeList = [
121             {
122                 title: this.translateService.instant('NSPRIMITIVE'),
123                 value: 'NS_Primitive'
124             },
125             {
126                 title: this.translateService.instant('VNFPRIMITIVE'),
127                 value: 'VNF_Primitive'
128             },
129             {
130                 title: this.translateService.instant('VDUPRIMITIVE'),
131                 value: 'VDU_Primitive'
132             },
133             {
134                 title: this.translateService.instant('KDUPRIMITIVE'),
135                 value: 'KDU_Primitive'
136             }
137         ];
138     }
139
140     /**
141      * Lifecyle Hooks the trigger before component is instantiate
142      */
143     public ngOnInit(): void {
144         /** Setting up initial value for NSD */
145         this.dataService.currentMessage.subscribe((event: NSData) => {
146             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
147                 this.nsdId = event.identifier;
148             }
149         });
150         this.initializeForm();
151     }
152
153     /** convenience getter for easy access to form fields */
154     get f(): FormGroup['controls'] { return this.primitiveForm.controls; }
155
156     /** initialize Forms @public */
157     public initializeForm(): void {
158         this.primitiveForm = this.formBuilder.group({
159             primitive: [null, [Validators.required]],
160             vnf_member_index: [null, [Validators.required]],
161             vdu_id: [null, [Validators.required]],
162             kdu_name: [null, [Validators.required]],
163             primitive_params: this.formBuilder.array([this.primitiveParamsBuilder()])
164         });
165     }
166
167     /** Generate primitive params @public */
168     public primitiveParamsBuilder(): FormGroup {
169         return this.formBuilder.group({
170             primitive_params_name: [null, [Validators.required]],
171             primitive_params_value: ['', [Validators.required]]
172         });
173     }
174
175     /** Handle FormArray Controls @public */
176     public getControls(): AbstractControl[] {
177         return (this.getFormControl('primitive_params') as FormArray).controls;
178     }
179
180     /** Push all primitive params on user's action @public */
181     public createPrimitiveParams(): void {
182         this.primitiveParams = this.getFormControl('primitive_params') as FormArray;
183         this.primitiveParams.push(this.primitiveParamsBuilder());
184     }
185
186     /** Remove primitive params on user's action @public */
187     public removePrimitiveParams(index: number): void {
188         this.primitiveParams.removeAt(index);
189     }
190
191     /** Execute Primitive @public */
192     public execPrimitive(): void {
193         this.submitted = true;
194         this.objectPrimitiveParams = {};
195         this.sharedService.cleanForm(this.primitiveForm);
196         if (this.primitiveForm.invalid) { return; } // Proceed, onces form is valid
197         this.primitiveForm.value.primitive_params.forEach((params: NSPrimitiveParams) => {
198             if (params.primitive_params_name !== null && params.primitive_params_value !== '') {
199                 this.objectPrimitiveParams[params.primitive_params_name] = params.primitive_params_value;
200             }
201         });
202         //Prepare primitive params
203         const primitiveParamsPayLoads: {} = {
204             primitive: this.primitiveForm.value.primitive,
205             primitive_params: this.objectPrimitiveParams
206         };
207         if (this.primitiveType === 'VNF_Primitive') {
208             // tslint:disable-next-line: no-string-literal
209             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
210         }
211         if (this.primitiveType === 'VDU_Primitive') {
212             // tslint:disable-next-line: no-string-literal
213             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
214             // tslint:disable-next-line: no-string-literal
215             primitiveParamsPayLoads['vdu_id'] = this.primitiveForm.value.vdu_id;
216         }
217         if (this.primitiveType === 'KDU_Primitive') {
218             // tslint:disable-next-line: no-string-literal
219             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
220             // tslint:disable-next-line: no-string-literal
221             primitiveParamsPayLoads['kdu_name'] = this.primitiveForm.value.kdu_name;
222         }
223         const apiURLHeader: APIURLHEADER = {
224             url: environment.NSDINSTANCES_URL + '/' + this.nsdId + '/action'
225         };
226         this.isLoadingResults = true;
227         this.restService.postResource(apiURLHeader, primitiveParamsPayLoads).subscribe((result: {}) => {
228             this.activeModal.dismiss();
229             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPRIMITIVE.EXECUTEDSUCCESSFULLY'));
230             this.isLoadingResults = false;
231         }, (error: ERRORDATA) => {
232             this.isLoadingResults = false;
233             this.restService.handleError(error, 'post');
234         });
235     }
236     /** Primitive type change event @public */
237     public primitiveTypeChange(data: { value: string }): void {
238         this.primitiveList = [];
239         this.primitiveParameter = [];
240         this.initializeForm();
241         if (data.value === 'NS_Primitive') {
242             this.getNSInfo(this.params.name);
243             this.setUpdateValueandValidation('vnf_member_index');
244         }
245         if (data.value === 'VNF_Primitive' || data.value === 'KDU_Primitive' || data.value === 'NS_Primitive') {
246             this.setUpdateValueandValidation('vdu_id');
247         }
248         if (data.value === 'VDU_Primitive' || data.value === 'VNF_Primitive' || data.value === 'NS_Primitive') {
249             this.setUpdateValueandValidation('kdu_name');
250         }
251     }
252     /** Member index change event */
253     public indexChange(data: {}, getType?: string): void {
254         this.getFormControl('vdu_id').setValue(null);
255         this.getFormControl('kdu_name').setValue(null);
256         if (data) {
257             this.getVnfdInfo(data['vnfd-id-ref'], getType);
258         } else {
259             this.primitiveList = [];
260             this.getFormControl('primitive').setValue(null);
261             this.primitiveParameter = [];
262         }
263     }
264     /** Get VDU/KDU primitive List for the selected event @public */
265     public getPrimitiveList(data: {}, selectedType: string): void {
266         this.primitiveList = data[selectedType + '-configuration']['config-primitive'];
267     }
268     /** Primivtive change event */
269     public primitiveChange(data: { parameter: {}[] }): void {
270         this.primitiveParameter = [];
271         const formArr: FormArray = this.getFormControl('primitive_params') as FormArray;
272         formArr.controls = [];
273         this.createPrimitiveParams();
274         if (data) {
275             this.updatePrimitive(data);
276         }
277     }
278     /** Generate vdu section @public */
279     public generateVDUData(vduData: VDUPRIMITIVELEVEL): VDUPRIMITIVELEVEL {
280         return {
281             id: vduData.id,
282             name: vduData.name,
283             'vdu-configuration': vduData['vdu-configuration']
284         };
285     }
286     /** Generate kdu section @public */
287     public generateKDUData(kduData: KDUPRIMITIVELEVEL): KDUPRIMITIVELEVEL {
288         return {
289             name: kduData.name,
290             'juju-bundle': kduData['juju-bundle'],
291             'kdu-configuration': kduData['kdu-configuration']
292         };
293     }
294     /** Used to set the validation and value and update the validation and value @public */
295     public setUpdateValueandValidation(formName: string): void {
296         this.getFormControl(formName).setValidators([]);
297         this.getFormControl(formName).updateValueAndValidity();
298     }
299     /** Update primitive value based on parameter */
300     private updatePrimitive(primitive: { parameter: {}[] }): void {
301         if (primitive.parameter) {
302             this.primitiveParameter = primitive.parameter;
303         } else {
304             this.primitiveParameter = [];
305             const formArr: AbstractControl[] = this.getControls();
306             formArr.forEach((formGp: FormGroup) => {
307                 formGp.controls.primitive_params_name.setValidators([]);
308                 formGp.controls.primitive_params_name.updateValueAndValidity();
309                 formGp.controls.primitive_params_value.setValidators([]);
310                 formGp.controls.primitive_params_value.updateValueAndValidity();
311             });
312         }
313     }
314     /** Get primivitive actions from vnfd data */
315     private getVnfdInfo(vnfdRef: string, getType?: string): void {
316         this.primitiveList = [];
317         this.primitiveParameter = [];
318         this.getFormControl('primitive').setValue(null);
319         const apiUrl: string = environment.VNFPACKAGES_URL + '?short-name=' + vnfdRef;
320         this.isLoadingResults = true;
321         this.restService.getResource(apiUrl)
322             .subscribe((vnfdInfo: {}) => {
323                 if (vnfdInfo[0]['vnf-configuration'] !== undefined && vnfdInfo[0]['vnf-configuration']) {
324                     this.getFormControl('vdu_id').setValidators([]);
325                     this.getFormControl('kdu_name').setValidators([]);
326                     this.primitiveList = vnfdInfo[0]['vnf-configuration']['config-primitive'];
327                 }
328                 if (getType === 'VDU_Primitive') {
329                     this.kduList = [];
330                     this.vduList = [];
331                     this.primitiveList = [];
332                     if (!isNullOrUndefined(vnfdInfo[0].vdu)) {
333                         vnfdInfo[0].vdu.forEach((vduData: VDUPRIMITIVELEVEL) => {
334                             if (vduData['vdu-configuration']) {
335                                 const vduDataObj: VDUPRIMITIVELEVEL = this.generateVDUData(vduData);
336                                 this.vduList.push(vduDataObj);
337                             }
338                         });
339                     }
340                 }
341                 if (getType === 'KDU_Primitive') {
342                     this.kduList = [];
343                     this.vduList = [];
344                     this.primitiveList = [];
345                     if (!isNullOrUndefined(vnfdInfo[0].kdu)) {
346                         vnfdInfo[0].kdu.forEach((kduData: KDUPRIMITIVELEVEL) => {
347                             if (kduData['kdu-configuration']) {
348                                 const kduDataObj: KDUPRIMITIVELEVEL = this.generateKDUData(kduData);
349                                 this.kduList.push(kduDataObj);
350                             }
351                         });
352                     }
353                 }
354                 this.isLoadingResults = false;
355             }, (error: ERRORDATA) => {
356                 this.isLoadingResults = false;
357                 this.restService.handleError(error, 'get');
358             });
359     }
360     /** Get primivitive actions from NSD data */
361     private getNSInfo(nsdRef: string): void {
362         this.primitiveList = [];
363         this.primitiveParameter = [];
364         this.getFormControl('primitive').setValue(null);
365         const apiUrl: string = environment.NSDESCRIPTORS_URL + '?short-name=' + nsdRef;
366         this.isLoadingResults = true;
367         this.restService.getResource(apiUrl)
368             .subscribe((nsdInfo: {}) => {
369                 if (!isNullOrUndefined(nsdInfo[0]['ns-configuration'])) {
370                     this.primitiveList = !isNullOrUndefined(nsdInfo[0]['ns-configuration']['config-primitive']) ?
371                         nsdInfo[0]['ns-configuration']['config-primitive'] : [];
372                 } else {
373                     this.primitiveList = [];
374                 }
375                 this.isLoadingResults = false;
376             }, (error: ERRORDATA) => {
377                 this.isLoadingResults = false;
378                 this.restService.handleError(error, 'get');
379             });
380     }
381     /** Used to get the AbstractControl of controlName passed @private */
382     private getFormControl(controlName: string): AbstractControl {
383         return this.primitiveForm.controls[controlName];
384     }
385 }