Added Grafana url setting in config panel
[src/xds/xds-agent.git] / webapp / src / app / @core-xds / services / config.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 } from '@angular/core';
20 import { CookieService } from 'ngx-cookie';
21 import { NbThemeService } from '@nebular/theme';
22
23 import { Observable } from 'rxjs/Observable';
24 import { BehaviorSubject } from 'rxjs/BehaviorSubject';
25
26 export interface IConfig {
27   language: string;
28   theme: string;
29   grafanaDashboardUrl: string;
30 }
31
32 @Injectable()
33 export class ConfigService {
34
35   public Conf$: Observable<IConfig>;
36
37   private confSubject: BehaviorSubject<IConfig>;
38   private confStore: IConfig;
39
40   private confDefault: IConfig = {
41     language: 'ENG',
42     theme: 'default',
43     grafanaDashboardUrl: 'http://localhost:3000',
44   };
45
46   constructor(
47     private cookie: CookieService,
48     private themeService: NbThemeService,
49   ) {
50     this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
51     this.Conf$ = this.confSubject.asObservable();
52
53     // Save selected theme in cookie
54     this.themeService.onThemeChange().subscribe(tm => {
55       if (typeof this.confStore === 'undefined') {
56         return;
57       }
58       if (tm.name !== this.confStore.theme) {
59         this.confStore.theme = tm.name;
60         this.save();
61       }
62     });
63
64     // Load initial config and apply it
65     this.load();
66     this.themeService.changeTheme(this.confStore.theme);
67   }
68
69   // Load config
70   load() {
71     // Try to retrieve previous config from cookie
72     const cookConf = this.cookie.getObject('xds-config');
73     if (cookConf != null) {
74       this.confStore = <IConfig>cookConf;
75       this.confSubject.next(Object.assign({}, this.confStore));
76     } else {
77       // Set default config
78       this.confStore = this.confDefault;
79       this.save();
80     }
81   }
82
83   // Save config into cookie
84   save(cfg?: IConfig) {
85     if (typeof cfg !== 'undefined') {
86       this.confStore = this.confDefault;
87     }
88
89     // Notify subscribers
90     this.confSubject.next(Object.assign({}, this.confStore));
91
92     this.cookie.putObject('xds-config', this.confStore);
93   }
94
95 }