168b278e258e6d109899897b098fcbe10a54496c
[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 }
30
31 @Injectable()
32 export class ConfigService {
33
34   public Conf$: Observable<IConfig>;
35
36   private confSubject: BehaviorSubject<IConfig>;
37   private confStore: IConfig;
38
39   constructor(
40     private cookie: CookieService,
41     private themeService: NbThemeService,
42   ) {
43     this.confSubject = <BehaviorSubject<IConfig>>new BehaviorSubject(this.confStore);
44     this.Conf$ = this.confSubject.asObservable();
45
46     // Load initial config and apply it
47     this.load();
48     this.themeService.changeTheme(this.confStore.theme);
49
50     // Save selected theme in cookie
51     this.themeService.onThemeChange().subscribe(tm => {
52       if (tm.name !== this.confStore.theme) {
53         this.confStore.theme = tm.name;
54         this.save();
55       }
56     });
57   }
58
59   // Load config
60   load() {
61     // Try to retrieve previous config from cookie
62     const cookConf = this.cookie.getObject('xds-config');
63     if (cookConf != null) {
64       this.confStore = <IConfig>cookConf;
65     } else {
66       // Set default config
67       this.confStore = {
68         language: 'ENG',
69         theme: 'default',
70       };
71     }
72   }
73
74   // Save config into cookie
75   save() {
76     // Notify subscribers
77     this.confSubject.next(Object.assign({}, this.confStore));
78
79     this.cookie.putObject('xds-config', this.confStore);
80   }
81
82 }