Angular upgrade
[osm/NG-UI.git] / src / app / wim-accounts / new-wim-account / NewWIMAccountComponent.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 WIM Account Component.
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, ElementRef, Injector, OnInit, ViewChild } from '@angular/core';
23 import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
24 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
25 import { TranslateService } from '@ngx-translate/core';
26 import { NotifierService } from 'angular-notifier';
27 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, TYPESECTION, WIM_TYPES } from 'CommonModel';
28 import { environment } from 'environment';
29 import * as jsyaml from 'js-yaml';
30 import { RestService } from 'RestService';
31 import { SharedService, isNullOrUndefined } from 'SharedService';
32
33 /**
34  * Creating component
35  * @Component takes NewWIMAccountComponent.html as template url
36  */
37 @Component({
38   templateUrl: './NewWIMAccountComponent.html',
39   styleUrls: ['./NewWIMAccountComponent.scss']
40 })
41 /** Exporting a class @exports NewWIMAccountComponent */
42 export class NewWIMAccountComponent implements OnInit {
43   /** To inject services @public */
44   public injector: Injector;
45
46   /** Setting wim types in array @public */
47   public wimType: TYPESECTION[];
48
49   /** Set WIM Type select to empty @public */
50   public wimTypeMod: string = null;
51
52   /** New WIM account form controls using formgroup @public */
53   public wimNewAccountForm: FormGroup;
54
55   /** Form submission Add */
56   public submitted: boolean = false;
57
58   /** Instance for active modal service @public */
59   public activeModal: NgbActiveModal;
60
61   /** Check the loading results for loader status @public */
62   public isLoadingResults: boolean = false;
63
64   /** Give the message for the loading @public */
65   public message: string = 'PLEASEWAIT';
66
67   /** Element ref for fileInputConfig @public */
68   @ViewChild('fileInputConfig', { static: true }) public fileInputConfig: ElementRef;
69
70   /** Element ref for fileInputConfig @public */
71   @ViewChild('fileInputConfigLabel', { static: true }) public fileInputConfigLabel: ElementRef;
72
73   /** Contains all methods related to shared @private */
74   public sharedService: SharedService;
75
76   /** Instance of the rest service @private */
77   private restService: RestService;
78
79   /** Controls the header form @private */
80   private headers: HttpHeaders;
81
82   /** FormBuilder instance added to the formBuilder @private */
83   private formBuilder: FormBuilder;
84
85   /** Notifier service to popup notification @private */
86   private notifierService: NotifierService;
87
88   /** Contains tranlsate instance @private */
89   private translateService: TranslateService;
90
91   /** convenience getter for easy access to form fields */
92   get f(): FormGroup['controls'] { return this.wimNewAccountForm.controls; }
93
94   constructor(injector: Injector) {
95     this.injector = injector;
96     this.restService = this.injector.get(RestService);
97     this.formBuilder = this.injector.get(FormBuilder);
98     this.notifierService = this.injector.get(NotifierService);
99     this.translateService = this.injector.get(TranslateService);
100     this.activeModal = this.injector.get(NgbActiveModal);
101     this.sharedService = this.injector.get(SharedService);
102
103     /** Initializing Form Action */
104     this.wimNewAccountForm = this.formBuilder.group({
105       name: ['', Validators.required],
106       wim_type: ['', Validators.required],
107       wim_url: ['', [Validators.required, Validators.pattern(this.sharedService.REGX_URL_PATTERN)]],
108       user: ['', Validators.required],
109       password: ['', Validators.required],
110       description: [null],
111       config: [null]
112     });
113   }
114
115   /**
116    * Lifecyle Hooks the trigger before component is instantiate
117    */
118   public ngOnInit(): void {
119     this.wimType = WIM_TYPES;
120     this.headers = new HttpHeaders({
121       Accept: 'application/json',
122       'Content-Type': 'application/json',
123       'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
124     });
125   }
126
127   /** On modal submit newWimAccountSubmit will called @public */
128   public newWimAccountSubmit(): void {
129     this.submitted = true;
130     const modalData: MODALCLOSERESPONSEDATA = {
131       message: 'Done'
132     };
133     this.sharedService.cleanForm(this.wimNewAccountForm);
134     if (this.wimNewAccountForm.value.description === '') {
135       this.wimNewAccountForm.value.description = null;
136     }
137     if (isNullOrUndefined(this.wimNewAccountForm.value.config) || this.wimNewAccountForm.value.config === '') {
138       delete this.wimNewAccountForm.value.config;
139     } else {
140       const validJSON: boolean = this.sharedService.checkJson(this.wimNewAccountForm.value.config);
141       if (validJSON) {
142         this.wimNewAccountForm.value.config = JSON.parse(this.wimNewAccountForm.value.config);
143       } else {
144         this.notifierService.notify('error', this.translateService.instant('INVALIDCONFIG'));
145         return;
146       }
147     }
148     if (!this.wimNewAccountForm.invalid) {
149       this.isLoadingResults = true;
150       const apiURLHeader: APIURLHEADER = {
151         url: environment.WIMACCOUNTS_URL,
152         httpOptions: { headers: this.headers }
153       };
154       this.restService.postResource(apiURLHeader, this.wimNewAccountForm.value)
155         .subscribe((result: {}) => {
156           this.activeModal.close(modalData);
157           this.isLoadingResults = false;
158           this.notifierService.notify('success', this.translateService.instant('PAGE.WIMACCOUNTS.CREATEDSUCCESSFULLY'));
159         }, (error: ERRORDATA) => {
160           this.restService.handleError(error, 'post');
161           this.isLoadingResults = false;
162         });
163     }
164   }
165
166   /** Config file process @private */
167   public configFile(files: FileList): void {
168     if (files && files.length === 1) {
169       this.sharedService.getFileString(files, 'yaml').then((fileContent: string): void => {
170         const getConfigJson: string = jsyaml.load(fileContent, { json: true });
171         this.wimNewAccountForm.get('config').setValue(JSON.stringify(getConfigJson));
172       }).catch((err: string): void => {
173         if (err === 'typeError') {
174           this.notifierService.notify('error', this.translateService.instant('YAMLFILETYPEERRROR'));
175         } else {
176           this.notifierService.notify('error', this.translateService.instant('ERROR'));
177         }
178         this.fileInputConfigLabel.nativeElement.innerText = this.translateService.instant('CHOOSEFILE');
179         this.fileInputConfig.nativeElement.value = null;
180       });
181     } else if (files && files.length > 1) {
182       this.notifierService.notify('error', this.translateService.instant('DROPFILESVALIDATION'));
183     }
184     this.fileInputConfigLabel.nativeElement.innerText = files[0].name;
185     this.fileInputConfig.nativeElement.value = null;
186   }
187 }