import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AuthService } from '../auth/auth.service';
import { MessageService as MessageServiceP } from 'node_modules/primeng/api';
import { SystemSettingClass } from '../interface/system-setting';
import { Observable, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppConfig {
    public onupdate: BehaviorSubject<boolean>;
    static systemSettings: SystemSettingClass[];
    static settings: any;
    private baseUrl: string;
    constructor(private http: Http, @Inject('BASE_URL') baseUrl: string,
        public httpc: HttpClient) {
        this.baseUrl = baseUrl;
        this.onupdate = new BehaviorSubject(false);
    }

    load(authService: AuthService, messageService: MessageServiceP) {
        const jsonFile = `assets/config/appsettings.json`;
        return new Promise<void>((resolve, reject) => {
            this.http.get(this.baseUrl + jsonFile).toPromise().then((response: Response) => {
                AppConfig.settings = <any>response.json();
                try {
                    authService.load();
                    //messageService.load();
                    this.getSystemSetting(messageService);
                } catch (error) { console.log(error); }
                resolve();
            }).catch((response: any) => {
                reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
            });
        });
    }

    getSystemSetting(messageService: MessageServiceP) {
        this.httpc.get<SystemSettingClass[]>(AppConfig.settings.UserManagerSettings.authority + 'api/SystemSettingApi/GetSimple', {
            // headers: this.httpHeaders,
        })
            .subscribe(res => {
                // console.log('res');
                // console.log(res);
                AppConfig.systemSettings = res;
                this.onupdate.next(true);
            },
                error => {
                    // console.error(error);
                    messageService.add({ severity: 'error', summary: 'Error', detail: 'System Setting Error: ' + error.error });
                }
            );

    }

}

