import { Injectable, Inject } from '@angular/core';
import { Location } from '@angular/common';
import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/throw';

import {
  RESTError,
  RESTClientError,
} from '../protocol';

export class RESTClient {
  constructor(
    private _baseURL: string,
    private _httpClient: HttpClient,
  ) {
  }

  public get httpClient(): HttpClient {
    return this._httpClient;
  }

  public request<T>(method: string, entry: string, options?: {
    body?: any;
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    responseType?: 'json';
    reportProgress?: boolean;
    withCredentials?: boolean;
  }): Observable<T> {
    return this._httpClient
      .request<T>(method, Location.joinWithSlash(this._baseURL, entry), options)
      .map(response => response)
      .catch((error: HttpErrorResponse) => {
        const restClientError: RESTClientError = {
          request: {
            method: method,
            entry: entry,
            options: options,
          },
          response: error.error,
        };

        console.error(restClientError);
        // const aryMsg = error.error.message.split('|');
        // const resError: RESTError = {
        //   code: error.error.code,
        //   message: aryMsg[0],
        //   data: aryMsg[1] === 'null' ? '' : aryMsg[1],
        // };
        return Observable.throw(restClientError);
      });
  }
}
