import { Http, RequestOptions, Response } from '@angular/http';

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { IConfig, CConfig } from './config.model';

import { TokenService } from '../token/token.service';

import { IApiError, IApiResponseError, IApiResponseSuccess, isApiResponseError } from '../token/apiresponse.model';

@Injectable()
export class ConfigService {
    configItems: IConfig;

    settings(key: string): Observable<string> {
        return this.config.map((val: IConfig): string => {
            if (this.configItems[key]) {
                return this.configItems[key];
            }
            return '';
        });
    }

    settingsNumeric(key: string): Observable<number> {
        return this.config.map((val: IConfig): number => {
            if (this.configItems[key] && Number(this.configItems[key])) {
                return Number(this.configItems[key]);
            }
            return 0;
        });
    }

    constructor(private http: Http, private tokenService: TokenService) { }

    get config(): Observable<IConfig> {
        if (this.configItems) {
            return Observable.of(this.configItems);
        }
        return this.http
                    .get(`${SETTINGS.API_URL}/general/Configs`,
                    new RequestOptions({ headers: this.tokenService.authorizationHeaders }))
            .map((response: Response) => {
                const data: IApiResponseError | IApiResponseSuccess<IConfig> = response.json();
                if (isApiResponseError(data)) {
                    return Observable.throw(data.error);
                }
                data.result = Object.assign(new CConfig(), data.result);
                return data.result;
            })
            .map((config: IConfig) => {
                if (config) {
                    this.configItems = config;
                    return config;
                }
            }).catch(this.handleError);
    }

    private handleError(error: IApiError): Observable<IConfig> {
        return Observable.throw(error.msg || error);
    }
}
