import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { BehaviorSubject } from 'rxjs';

import { IAppSettings } from '../models/app-settings';


@Injectable({ providedIn: "root" })
export class ConfigurationHelper {
    private static settingsSource = new BehaviorSubject<IAppSettings>(null);
    public static settings = ConfigurationHelper.settingsSource.asObservable();
    
    constructor(private http: HttpClient) {}

    load(env: string) {
        const jsonFile = `/config/config.${env}.json`;

        return new Promise<void>((resolve, reject) => {
            this.http.get(jsonFile)
                     .toPromise()
                     .then((response : IAppSettings) => {
                        ConfigurationHelper.settingsSource.next(<IAppSettings>response);
                        resolve();
                     })
                     .catch((response: any) => {
                        reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
                     });
        });
    }
}