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 { CCurrencies, ICurrencies, ICurrency } from './currency.model';

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

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

@Injectable()
export class CurrencyService {
  // currencies: ICurrencies;

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

  getCurrencies(currency: string): Observable<ICurrencies> {
    // if (this.currencies) {
    //     return Observable.of(this.currencies);
    // }
    return this.http
      .get(`${SETTINGS.API_URL}/general/Currencies/` + (currency ? currency : ''),
        new RequestOptions({headers: this.tokenService.authorizationHeaders}))
      .map((response: Response) => {
        const data: IApiResponseError | IApiResponseSuccess<ICurrencies> = response.json();
        if (isApiResponseError(data)) {
          return Observable.throw(data.error);
        }
        data.result = Object.assign(new CCurrencies(), data.result);
        return data.result;
      })
      .map((currencies: ICurrencies) => {
        if (currencies.items.length > 0) {
          // this.currencies = currencies;
          return currencies;
        }
      }).catch(this.handleError);
  }

  getFilterCurrencies(availableKnoks: boolean = false, activeKnoks: boolean = false, endedKnoks: boolean = false, userId: number = 0): Observable<ICurrencies> {
    // if (this.currencies) {
    //     return Observable.of(this.currencies);
    // }
    return this.http
      .get(`${SETTINGS.API_URL}/general/FilterCurrencies/`,
        new RequestOptions({headers: this.tokenService.authorizationHeaders, params: {availableKnoks: availableKnoks, activeKnoks: activeKnoks, endedKnoks: endedKnoks, userId: userId}}))
      .map((response: Response) => {
        const data: IApiResponseError | IApiResponseSuccess<ICurrencies> = response.json();
        if (isApiResponseError(data)) {
          return Observable.throw(data.error);
        }
        data.result = Object.assign(new CCurrencies(), data.result);
        return data.result;
      })
      .map((currencies: ICurrencies) => {
        if (currencies.items.length > 0) {
          // this.currencies = currencies;
          return currencies;
        }
      }).catch(this.handleError);
  }

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