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 { IAnalysisTag, IAnalysisTags } from '../knok/knok.model';

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

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

@Injectable()
export class TagService {
    taTagItems: IAnalysisTags;
    faTagItems: IAnalysisTags;

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

    get taTags(): Observable<IAnalysisTags> {
        return this.getTags(true);
    }

    get faTags(): Observable<IAnalysisTags> {
        return this.getTags(false);
    }

    private getTags(isTechnical: boolean): Observable<IAnalysisTags> {
        if (isTechnical && this.taTagItems) {
            return Observable.of(this.taTagItems);
        }
        if (!isTechnical && this.faTagItems) {
            return Observable.of(this.faTagItems);
        }
        return this.http
                    .get(`${SETTINGS.API_URL}/general/Tags/` + (isTechnical ? 1 : 2).toString(),
                    new RequestOptions({ headers: this.tokenService.authorizationHeaders }))
            .map((response: Response) => {
                const data: IApiResponseError | IApiResponseSuccess<IAnalysisTags> = response.json();
                if (isApiResponseError(data)) {
                    return Observable.throw(data.error);
                }
                return data.result;
            })
            .map((tags: IAnalysisTags) => {
                if (tags.items.length > 0) {
                    if (isTechnical) {
                        this.taTagItems = tags;
                    } else {
                        this.faTagItems = tags;
                    }

                    return tags;
                }
            }).catch(this.handleError);
    }

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