46366e0979594c1cf4bc035669764c095c311bae
[osm/NG-UI.git] / src / app / packages / ns-packages / NSPackagesComponent.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-Packages component.
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, ElementRef, Injector, OnInit, ViewChild } from '@angular/core';
23 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { NotifierService } from 'angular-notifier';
26 import { APIURLHEADER, ERRORDATA } from 'CommonModel';
27 import { ComposePackages } from 'ComposePackages';
28 import { DataService } from 'DataService';
29 import { environment } from 'environment';
30 import { LocalDataSource } from 'ng2-smart-table';
31 import { NSData, NSDDetails } from 'NSDModel';
32 import { NsPackagesActionComponent } from 'NsPackagesAction';
33 import { RestService } from 'RestService';
34 import { Subscription } from 'rxjs';
35 import { SharedService } from 'SharedService';
36
37 /**
38  * Creating component
39  * @Component takes NSPackagesComponent.html as template url
40  */
41 @Component({
42     selector: 'app-ns-packages',
43     templateUrl: './NSPackagesComponent.html',
44     styleUrls: ['./NSPackagesComponent.scss']
45 })
46
47 /** Exporting a class @exports NSPackagesComponent */
48 export class NSPackagesComponent implements OnInit {
49     /** To inject services @public */
50     public injector: Injector;
51
52     /** Formation of appropriate Data for LocalDatasource @public */
53     public dataSource: LocalDataSource = new LocalDataSource();
54
55     /** handle translate @public */
56     public translateService: TranslateService;
57
58     /** Columns list of the smart table @public */
59     public columnLists: object = {};
60
61     /** Settings for smarttable to populate the table with columns @public */
62     public settings: object = {};
63
64     /** Check the loading results @public */
65     public isLoadingResults: boolean = true;
66
67     /** Give the message for the loading @public */
68     public message: string = 'PLEASEWAIT';
69
70     /** Class for empty and present data @public */
71     public checkDataClass: string;
72
73     /** Element ref for fileInput @public */
74     @ViewChild('fileInput', { static: true }) public fileInput: ElementRef;
75
76     /** Instance of the rest service @private */
77     private restService: RestService;
78
79     /** dataService to pass the data from one component to another @private */
80     private dataService: DataService;
81
82     /** Formation of appropriate Data for LocalDatasource @private */
83     private nsData: NSData[] = [];
84
85     /** Contains all methods related to shared @private */
86     private sharedService: SharedService;
87
88     /** variables holds file information @private */
89     private fileData: string | ArrayBuffer;
90
91     /** Controls the header form @private */
92     private headers: HttpHeaders;
93
94     /** Notifier service to popup notification @private */
95     private notifierService: NotifierService;
96
97     /** Instance of the modal service @private */
98     private modalService: NgbModal;
99
100     /** Instance of subscriptions @private */
101     private generateDataSub: Subscription;
102
103     constructor(injector: Injector) {
104         this.injector = injector;
105         this.restService = this.injector.get(RestService);
106         this.dataService = this.injector.get(DataService);
107         this.sharedService = this.injector.get(SharedService);
108         this.translateService = this.injector.get(TranslateService);
109         this.notifierService = this.injector.get(NotifierService);
110         this.modalService = this.injector.get(NgbModal);
111     }
112
113     /** Lifecyle Hooks the trigger before component is instantiate @public */
114     public ngOnInit(): void {
115         this.generateColumns();
116         this.generateSettings();
117         this.generateData();
118         this.headers = new HttpHeaders({
119             'Content-Type': 'application/gzip',
120             Accept: 'application/json',
121             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
122         });
123         this.generateDataSub = this.sharedService.dataEvent.subscribe(() => { this.generateData(); });
124     }
125
126     /** smart table Header Colums @public */
127     public generateColumns(): void {
128         this.columnLists = {
129             shortName: { title: this.translateService.instant('SHORTNAME'), width: '15%', sortDirection: 'asc' },
130             identifier: { title: this.translateService.instant('IDENTIFIER'), width: '20%' },
131             description: { title: this.translateService.instant('DESCRIPTION'), width: '25%' },
132             vendor: { title: this.translateService.instant('VENDOR'), width: '15%' },
133             version: { title: this.translateService.instant('VERSION'), width: '10%' },
134             Actions: {
135                 name: 'Actions', width: '15%', filter: false, sort: false, type: 'custom',
136                 title: this.translateService.instant('ACTIONS'),
137                 valuePrepareFunction: (cell: NSData, row: NSData): NSData => row, renderComponent: NsPackagesActionComponent
138             }
139         };
140     }
141
142     /** smart table Data Settings @public */
143     public generateSettings(): void {
144         this.settings = {
145             edit: {
146                 editButtonContent: '<i class="fa fa-edit" title="Edit"></i>',
147                 confirmSave: true
148             },
149             delete: {
150                 deleteButtonContent: '<i class="far fa-trash-alt" title="delete"></i>',
151                 confirmDelete: true
152             },
153             columns: this.columnLists,
154             actions: {
155                 add: false,
156                 edit: false,
157                 delete: false,
158                 position: 'right'
159             },
160             attr: this.sharedService.tableClassConfig(),
161             pager: this.sharedService.paginationPagerConfig(),
162             noDataMessage: this.translateService.instant('NODATAMSG')
163         };
164     }
165
166     /** smart table listing manipulation @public */
167     public onChange(perPageValue: number): void {
168         this.dataSource.setPaging(1, perPageValue, true);
169     }
170
171     /** smart table listing manipulation @public */
172     public onUserRowSelect(event: MessageEvent): void {
173         Object.assign(event.data, { page: 'ns-package' });
174         this.dataService.changeMessage(event.data);
175     }
176
177     /** Drag and drop feature and fetchind the details of files  @public */
178     public filesDropped(files: FileList): void {
179         if (files && files.length === 1) {
180             this.isLoadingResults = true;
181             this.sharedService.getFileString(files, 'gz').then((fileContent: ArrayBuffer): void => {
182                 const apiURLHeader: APIURLHEADER = {
183                     url: environment.NSDESCRIPTORSCONTENT_URL,
184                     httpOptions: { headers: this.headers }
185                 };
186                 this.saveFileData(apiURLHeader, fileContent);
187             }).catch((err: string): void => {
188                 this.isLoadingResults = false;
189                 if (err === 'typeError') {
190                     this.notifierService.notify('error', this.translateService.instant('GZFILETYPEERRROR'));
191                 } else {
192                     this.notifierService.notify('error', this.translateService.instant('ERROR'));
193                 }
194             });
195         } else if (files && files.length > 1) {
196             this.notifierService.notify('error', this.translateService.instant('DROPFILESVALIDATION'));
197         }
198     }
199
200     /** Post the droped files and reload the page @public */
201     public saveFileData(urlHeader: APIURLHEADER, fileData: {}): void {
202         this.fileInput.nativeElement.value = null;
203         this.restService.postResource(urlHeader, fileData).subscribe((result: {}) => {
204             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPACKAGE.CREATEDSUCCESSFULLY'));
205             this.generateData();
206         }, (error: ERRORDATA) => {
207             this.restService.handleError(error, 'post');
208             this.isLoadingResults = false;
209         });
210     }
211
212     /** Generate nsData object from loop and return for the datasource @public */
213     public generateNSData(nsdpackagedata: NSDDetails): NSData {
214         return {
215             shortName: nsdpackagedata['short-name'],
216             identifier: nsdpackagedata._id,
217             description: nsdpackagedata.description,
218             vendor: nsdpackagedata.vendor,
219             version: nsdpackagedata.version
220         };
221     }
222
223     /** Fetching the data from server to Load in the smarttable @public */
224     public generateData(): void {
225         this.isLoadingResults = true;
226         this.restService.getResource(environment.NSDESCRIPTORSCONTENT_URL).subscribe((nsdPackageData: NSDDetails[]) => {
227             this.nsData = [];
228             nsdPackageData.forEach((nsdpackagedata: NSDDetails) => {
229                 const nsDataObj: NSData = this.generateNSData(nsdpackagedata);
230                 this.nsData.push(nsDataObj);
231             });
232             if (this.nsData.length > 0) {
233                 this.checkDataClass = 'dataTables_present';
234             } else {
235                 this.checkDataClass = 'dataTables_empty';
236             }
237             this.dataSource.load(this.nsData).then((data: boolean) => {
238                 this.isLoadingResults = false;
239             }).catch(() => {
240                 this.isLoadingResults = false;
241             });
242         }, (error: ERRORDATA) => {
243             this.restService.handleError(error, 'get');
244             this.isLoadingResults = false;
245         });
246     }
247     /** Handle compose new ns package method  @public */
248     public composeNSPackage(): void {
249         this.modalService.open(ComposePackages, { backdrop: 'static' }).componentInstance.params = { page: 'ns-package' };
250     }
251
252     /**
253      * Lifecyle hook which get trigger on component destruction
254      */
255     public ngOnDestroy(): void {
256         this.generateDataSub.unsubscribe();
257     }
258 }