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 { CExchanges, IExchange, IExchanges } from './exchange.model';

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

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

@Injectable()
export class ExchangeService {
    // exchanges: IExchanges;

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

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

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

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