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 { ILanguage, ILanguages } from './language.model';

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

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

@Injectable()
export class LanguageService {
    languages: ILanguages;

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

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

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