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