1086f49c688c232314ec14b889f55e0a35f81b95
[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 { 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     /** FormBuilder instance added to the formBuilder @private */
88     private formBuilder: FormBuilder;
89
90     /** Utilizes rest service for any CRUD operations @private */
91     private restService: RestService;
92
93     /** packages data service collections @private */
94     private dataService: DataService;
95
96     /** Contains tranlsate instance @private */
97     private translateService: TranslateService;
98
99     /** Notifier service to popup notification @private */
100     private notifierService: NotifierService;
101
102     /** Contains all methods related to shared @private */
103     private sharedService: SharedService;
104
105     /** Contains objects that is used to convert key/value pair @private */
106     private objectPrimitiveParams: {} = {};
107
108     constructor(injector: Injector) {
109         this.injector = injector;
110         this.restService = this.injector.get(RestService);
111         this.dataService = this.injector.get(DataService);
112         this.translateService = this.injector.get(TranslateService);
113         this.notifierService = this.injector.get(NotifierService);
114         this.sharedService = this.injector.get(SharedService);
115         this.activeModal = this.injector.get(NgbActiveModal);
116         this.formBuilder = this.injector.get(FormBuilder);
117         this.primitiveTypeList = [
118             {
119                 title: this.translateService.instant('NSPRIMITIVE'),
120                 value: 'NS_Primitive'
121             },
122             {
123                 title: this.translateService.instant('VNFPRIMITIVE'),
124                 value: 'VNF_Primitive'
125             },
126             {
127                 title: this.translateService.instant('VDUPRIMITIVE'),
128                 value: 'VDU_Primitive'
129             }
130         ];
131     }
132
133     /**
134      * Lifecyle Hooks the trigger before component is instantiate
135      */
136     public ngOnInit(): void {
137         /** Setting up initial value for NSD */
138         this.dataService.currentMessage.subscribe((event: NSData) => {
139             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
140                 this.nsdId = event.identifier;
141             }
142         });
143         this.initializeForm();
144     }
145
146     /** convenience getter for easy access to form fields */
147     get f(): FormGroup['controls'] { return this.primitiveForm.controls; }
148
149     /** initialize Forms @public */
150     public initializeForm(): void {
151         this.primitiveForm = this.formBuilder.group({
152             primitive: [null, [Validators.required]],
153             vnf_member_index: [null, [Validators.required]],
154             vdu_id: [null, [Validators.required]],
155             primitive_params: this.formBuilder.array([this.primitiveParamsBuilder()])
156         });
157     }
158
159     /** Generate primitive params @public */
160     public primitiveParamsBuilder(): FormGroup {
161         return this.formBuilder.group({
162             primitive_params_name: [null, [Validators.required]],
163             primitive_params_value: ['', [Validators.required]]
164         });
165     }
166
167     /** Handle FormArray Controls @public */
168     public getControls(): AbstractControl[] {
169         return (this.getFormControl('primitive_params') as FormArray).controls;
170     }
171
172     /** Push all primitive params on user's action @public */
173     public createPrimitiveParams(): void {
174         this.primitiveParams = this.getFormControl('primitive_params') as FormArray;
175         this.primitiveParams.push(this.primitiveParamsBuilder());
176     }
177
178     /** Remove primitive params on user's action @public */
179     public removePrimitiveParams(index: number): void {
180         this.primitiveParams.removeAt(index);
181     }
182
183     /** Execute NS Primitive @public */
184     public execNSPrimitive(): void {
185         this.submitted = true;
186         this.objectPrimitiveParams = {};
187         this.sharedService.cleanForm(this.primitiveForm);
188         if (this.primitiveForm.invalid) { return; } // Proceed, onces form is valid
189         this.primitiveForm.value.primitive_params.forEach((params: NSPrimitiveParams) => {
190             if (params.primitive_params_name !== null && params.primitive_params_value !== '') {
191                 this.objectPrimitiveParams[params.primitive_params_name] = params.primitive_params_value;
192             }
193         });
194         //Prepare primitive params
195         const primitiveParamsPayLoads: {} = {
196             primitive: this.primitiveForm.value.primitive,
197             primitive_params: this.objectPrimitiveParams
198         };
199         if (this.primitiveType === 'VNF_Primitive') {
200             // tslint:disable-next-line: no-string-literal
201             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
202         }
203         if (this.primitiveType === 'VDU_Primitive') {
204             // tslint:disable-next-line: no-string-literal
205             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
206             // tslint:disable-next-line: no-string-literal
207             primitiveParamsPayLoads['vdu_id'] = this.primitiveForm.value.vdu_id;
208         }
209         const apiURLHeader: APIURLHEADER = {
210             url: environment.NSDINSTANCES_URL + '/' + this.nsdId + '/action'
211         };
212         this.isLoadingResults = true;
213         this.restService.postResource(apiURLHeader, primitiveParamsPayLoads).subscribe((result: {}) => {
214             this.activeModal.dismiss();
215             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPRIMITIVE.EXECUTEDSUCCESSFULLY'));
216             this.isLoadingResults = false;
217         }, (error: ERRORDATA) => {
218             this.isLoadingResults = false;
219             this.restService.handleError(error, 'post');
220         });
221     }
222     /** Primitive type change event @public */
223     public primitiveTypeChange(data: { value: string }): void {
224         this.primitiveList = [];
225         this.primitiveParameter = [];
226         this.initializeForm();
227         if (data.value === 'NS_Primitive') {
228             this.getNSInfo(this.params.name);
229             this.getFormControl('vnf_member_index').setValidators([]);
230             this.getFormControl('vnf_member_index').updateValueAndValidity();
231             this.getFormControl('vdu_id').setValidators([]);
232             this.getFormControl('vdu_id').updateValueAndValidity();
233         } else if (data.value === 'VNF_Primitive') {
234             this.getFormControl('vdu_id').setValidators([]);
235             this.getFormControl('vdu_id').updateValueAndValidity();
236         }
237     }
238     /** Member index change event */
239     public indexChange(data: {}, getType?: string): void {
240         this.getFormControl('vdu_id').setValue(null);
241         if (data) {
242             this.getVnfdInfo(data['vnfd-id-ref'], getType);
243         } else {
244             this.primitiveList = [];
245             this.getFormControl('primitive').setValue(null);
246             this.primitiveParameter = [];
247         }
248     }
249     /** Get VDU Primitive from selected VDU id/name change event */
250     public getVDUPrimitive(data: {}): void {
251         this.primitiveList = data['vdu-configuration']['config-primitive'];
252     }
253     /** Primivtive change event */
254     public primitiveChange(data: { parameter: {}[] }): void {
255         this.primitiveParameter = [];
256         const formArr: FormArray = this.getFormControl('primitive_params') as FormArray;
257         formArr.controls = [];
258         this.createPrimitiveParams();
259         if (data) {
260             this.updatePrimitive(data);
261         }
262     }
263     /** Generate vdu section @public */
264     public generateVDUData(vduData: VDUPRIMITIVELEVEL): VDUPRIMITIVELEVEL {
265         return {
266             id: vduData.id,
267             name: vduData.name,
268             'vdu-configuration': vduData['vdu-configuration']
269         };
270     }
271     /** Update primitive value based on parameter */
272     private updatePrimitive(primitive: { parameter: {}[] }): void {
273         if (primitive.parameter) {
274             this.primitiveParameter = primitive.parameter;
275         } else {
276             this.primitiveParameter = [];
277             const formArr: AbstractControl[] = this.getControls();
278             formArr.forEach((formGp: FormGroup) => {
279                 formGp.controls.primitive_params_name.setValidators([]);
280                 formGp.controls.primitive_params_name.updateValueAndValidity();
281                 formGp.controls.primitive_params_value.setValidators([]);
282                 formGp.controls.primitive_params_value.updateValueAndValidity();
283             });
284         }
285     }
286     /** Get primivitive actions from vnfd data */
287     private getVnfdInfo(vnfdRef: string, getType?: string): void {
288         this.primitiveList = [];
289         this.primitiveParameter = [];
290         this.getFormControl('primitive').setValue(null);
291         const apiUrl: string = environment.VNFPACKAGES_URL + '?short-name=' + vnfdRef;
292         this.isLoadingResults = true;
293         this.restService.getResource(apiUrl)
294             .subscribe((vnfdInfo: {}) => {
295                 if (vnfdInfo[0]['vnf-configuration'] !== undefined && vnfdInfo[0]['vnf-configuration']) {
296                     this.getFormControl('vdu_id').setValidators([]);
297                     this.primitiveList = vnfdInfo[0]['vnf-configuration']['config-primitive'];
298                 }
299                 if (getType === 'VDU_Primitive') {
300                     this.vduList = [];
301                     this.primitiveList = [];
302                     vnfdInfo[0].vdu.forEach((vduData: VDUPRIMITIVELEVEL) => {
303                         if (vduData['vdu-configuration']) {
304                             const vduDataObj: VDUPRIMITIVELEVEL = this.generateVDUData(vduData);
305                             this.vduList.push(vduDataObj);
306                         }
307                     });
308                 }
309                 this.isLoadingResults = false;
310             }, (error: ERRORDATA) => {
311                 this.isLoadingResults = false;
312                 this.restService.handleError(error, 'get');
313             });
314     }
315     /** Get primivitive actions from NSD data */
316     private getNSInfo(nsdRef: string): void {
317         this.primitiveList = [];
318         this.primitiveParameter = [];
319         this.getFormControl('primitive').setValue(null);
320         const apiUrl: string = environment.NSDESCRIPTORS_URL + '?short-name=' + nsdRef;
321         this.isLoadingResults = true;
322         this.restService.getResource(apiUrl)
323             .subscribe((nsdInfo: {}) => {
324                 if (!isNullOrUndefined(nsdInfo[0]['ns-configuration'])) {
325                     this.primitiveList = !isNullOrUndefined(nsdInfo[0]['ns-configuration']['config-primitive']) ?
326                     nsdInfo[0]['ns-configuration']['config-primitive'] : [];
327                 } else {
328                     this.primitiveList = [];
329                 }
330                 this.isLoadingResults = false;
331             }, (error: ERRORDATA) => {
332                 this.isLoadingResults = false;
333                 this.restService.handleError(error, 'get');
334             });
335     }
336     /** Used to get the AbstractControl of controlName passed @private */
337     private getFormControl(controlName: string): AbstractControl {
338         return this.primitiveForm.controls[controlName];
339     }
340 }