Initial Commit - NG UI
[osm/NG-UI.git] / src / app / instances / pdu-instances / add-pdu-instances / AddPDUInstancesComponent.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 ADD PDU Instances Component
20  */
21 import { Component, Injector, Input, OnInit, Output } 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, MODALCLOSERESPONSEDATA } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { PDUInstanceDetails } from 'PDUInstanceModel';
30 import { RestService } from 'RestService';
31 import { SharedService } from 'SharedService';
32 import { VimAccountDetails } from 'VimAccountModel';
33
34 /**
35  * Creating component
36  * @Component takes AddPDUInstancesComponent.html as template url
37  */
38 @Component({
39     templateUrl: './AddPDUInstancesComponent.html',
40     styleUrls: ['./AddPDUInstancesComponent.scss']
41 })
42 /** Exporting a class @exports AddPDUInstancesComponent */
43 export class AddPDUInstancesComponent implements OnInit {
44     /** Form valid on submit trigger @public */
45     public submitted: boolean = false;
46
47     /** To inject services @public */
48     public injector: Injector;
49
50     /** Instance for active modal service @public */
51     public activeModal: NgbActiveModal;
52
53     /** FormGroup instance added to the form @ html @public */
54     public pduInstancesForm: FormGroup;
55
56     /** Primitive params array @public */
57     public pduInterfaces: FormArray;
58
59     /** Variable set for twoway binding @public */
60     public pduInstanceId: string;
61
62     /** Set mgmt field to empty on load @public */
63     public selectedMgmt: string;
64
65     /** Set vim field to empty on load @public */
66     public selectedVIM: string;
67
68     /** Contains boolean value as select options for mgmt @public */
69     public mgmtState: {}[] = [{ name: 'True', value: true }, { name: 'False', value: false }];
70
71     /** Input contains Modal dialog component Instance @private */
72     @Input() public title: string;
73
74     /** Contains all the vim accounts list @public */
75     public vimAccountSelect: VimAccountDetails;
76
77     /** Check the loading results @public */
78     public isLoadingResults: boolean = false;
79
80     /** Give the message for the loading @public */
81     public message: string = 'PLEASEWAIT';
82
83     /** FormBuilder instance added to the formBuilder @private */
84     private formBuilder: FormBuilder;
85
86     /** Utilizes rest service for any CRUD operations @private */
87     private restService: RestService;
88
89     /** packages data service collections @private */
90     private dataService: DataService;
91
92     /** Contains tranlsate instance @private */
93     private translateService: TranslateService;
94
95     /** Notifier service to popup notification @private */
96     private notifierService: NotifierService;
97
98     /** Contains all methods related to shared @private */
99     private sharedService: SharedService;
100
101     constructor(injector: Injector) {
102         this.injector = injector;
103         this.restService = this.injector.get(RestService);
104         this.dataService = this.injector.get(DataService);
105         this.translateService = this.injector.get(TranslateService);
106         this.notifierService = this.injector.get(NotifierService);
107         this.sharedService = this.injector.get(SharedService);
108         this.activeModal = this.injector.get(NgbActiveModal);
109         this.formBuilder = this.injector.get(FormBuilder);
110     }
111
112     /**
113      * Lifecyle Hooks the trigger before component is instantiate
114      */
115     public ngOnInit(): void {
116         /** Setting up initial value for NSD */
117         this.dataService.currentMessage.subscribe((event: PDUInstanceDetails) => {
118             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
119                 this.pduInstanceId = event.identifier;
120             }
121         });
122         this.generateVIMAccounts();
123         this.initializeForm();
124     }
125
126     /** convenience getter for easy access to form fields */
127     get f(): FormGroup['controls'] { return this.pduInstancesForm.controls; }
128
129     /** initialize Forms @public */
130     public initializeForm(): void {
131         this.pduInstancesForm = this.formBuilder.group({
132             name: ['', [Validators.required]],
133             type: ['', [Validators.required]],
134             vim_accounts: ['', [Validators.required]],
135             interfaces: this.formBuilder.array([this.interfacesBuilder()])
136         });
137     }
138
139     /** Generate interfaces fields @public */
140     public interfacesBuilder(): FormGroup {
141         return this.formBuilder.group({
142             name: ['', [Validators.required]],
143             'ip-address': ['', [Validators.required, Validators.pattern(this.sharedService.REGX_IP_PATTERN)]],
144             mgmt: ['', [Validators.required]],
145             'vim-network-name': ['', [Validators.required]]
146         });
147     }
148
149     /** Handle FormArray Controls @public */
150     public getControls(): AbstractControl[] {
151         // tslint:disable-next-line:no-backbone-get-set-outside-model
152         return (this.pduInstancesForm.get('interfaces') as FormArray).controls;
153     }
154
155     /** Push all primitive params on user's action @public */
156     public createInterfaces(): void {
157         // tslint:disable-next-line:no-backbone-get-set-outside-model
158         this.pduInterfaces = this.pduInstancesForm.get('interfaces') as FormArray;
159         this.pduInterfaces.push(this.interfacesBuilder());
160     }
161
162     /** Remove interfaces on user's action @public */
163     public removeInterfaces(index: number): void {
164         this.pduInterfaces.removeAt(index);
165     }
166
167     /** Execute New PDU Instances @public */
168     public createPDUInstances(): void {
169         this.submitted = true;
170         this.sharedService.cleanForm(this.pduInstancesForm);
171         if (this.pduInstancesForm.invalid) { return; } // Proceed, onces form is valid
172         this.isLoadingResults = true;
173         const modalData: MODALCLOSERESPONSEDATA = {
174             message: 'Done'
175         };
176         const apiURLHeader: APIURLHEADER = {
177             url: environment.PDUINSTANCE_URL
178         };
179         this.restService.postResource(apiURLHeader, this.pduInstancesForm.value).subscribe((result: {}) => {
180             this.activeModal.close(modalData);
181             this.notifierService.notify('success', this.translateService.instant('PAGE.PDUINSTANCE.CREATEDSUCCESSFULLY'));
182             this.isLoadingResults = false;
183         }, (error: ERRORDATA) => {
184                 this.restService.handleError(error, 'post');
185                 this.isLoadingResults = false;
186         });
187     }
188
189     /** Generate vim accounts list @public */
190     public generateVIMAccounts(): void {
191         this.restService.getResource(environment.VIMACCOUNTS_URL).subscribe((vimData: VimAccountDetails) => {
192             this.vimAccountSelect = vimData;
193         }, (error: ERRORDATA) => {
194             this.restService.handleError(error, 'get');
195         });
196     }
197 }