Migration to AGL gerrit (update go import)
[src/xds/xds-agent.git] / webapp / src / app / @core-xds / services / alert.service.ts
1 /**
2 * @license
3 * Copyright (C) 2017-2018 "IoT.bzh"
4 * Author Sebastien Douheret <sebastien@iot.bzh>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 import { Injectable, SecurityContext } from '@angular/core';
20 import { Observable } from 'rxjs/Observable';
21 import { Subject } from 'rxjs/Subject';
22
23
24 export type AlertType = 'error' | 'warning' | 'info' | 'success';
25
26 export interface IAlert {
27   type: AlertType;
28   msg: string;
29   show?: boolean;
30   dismissible?: boolean;
31   dismissTimeout?: number;     // close alert after this time (in seconds)
32   id?: number;
33 }
34
35 @Injectable()
36 export class AlertService {
37   public alerts: Observable<IAlert[]>;
38
39   private _alerts: IAlert[];
40   private alertsSubject = <Subject<IAlert[]>>new Subject();
41   private uid = 0;
42   private defaultDismissTmo = 5; // in seconds
43
44   constructor() {
45     this.alerts = this.alertsSubject.asObservable();
46     this._alerts = [];
47     this.uid = 0;
48   }
49
50   public error(msg: string, dismissTime?: number) {
51     this.add({
52       type: 'error', msg: msg, dismissible: true, dismissTimeout: dismissTime,
53     });
54   }
55
56   public warning(msg: string, dismissible?: boolean) {
57     this.add({ type: 'warning', msg: msg, dismissible: true, dismissTimeout: (dismissible ? this.defaultDismissTmo : 0) });
58   }
59
60   public info(msg: string) {
61     this.add({ type: 'info', msg: msg, dismissible: true, dismissTimeout: this.defaultDismissTmo });
62   }
63
64   public add(al: IAlert) {
65     const msg = String(al.msg).replace('\n', '<br>');
66     // this._alerts.push({
67     this._alerts = [{
68       show: true,
69       type: al.type,
70       msg: msg,
71       dismissible: al.dismissible || true,
72       dismissTimeout: (al.dismissTimeout * 1000) || 0,
73       id: this.uid,
74     }];
75     this.uid += 1;
76     this.alertsSubject.next(this._alerts);
77
78   }
79
80   public del(al: IAlert) {
81     /*
82     const idx = this._alerts.findIndex((a) => a.id === al.id);
83     if (idx > -1) {
84       this._alerts.splice(idx, 1);
85       this.alertsSubject.next(this._alerts);
86     }
87     */
88     this._alerts = [];
89     this.alertsSubject.next(this._alerts);
90   }
91 }