import { environment } from '../../../environments/environment';

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Http, RequestOptions, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

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


const serverApiUrl = environment.serverApiUrl;
const API_IDENTIFIER = environment.apiIdentifier;

@Injectable()
export class UsersService {

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

  loadUsers(): Promise<any[]> {
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      Authorization: this.tokenService.authorization
    });
    let requestOptions: RequestOptions = new RequestOptions({ headers });
    return this.http.get(
      `${serverApiUrl}/Backoffice/users`, requestOptions)
      .map((res: Response) => res.json())
      .map((json) => json.result.items)
      // .do(data => console.log('server data:', data))  // debug
      .toPromise()
      .catch(e => this.handleError(e));
  }
  getUser(userId: Number): Promise<any> {
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      Authorization: this.tokenService.authorization
    });
    let requestOptions: RequestOptions = new RequestOptions({ headers });
    return this.http.get(
      `${serverApiUrl}/Backoffice/users?u=${userId}`, requestOptions)
      .map((res: Response) => res.json())
      .map((json) => json.result.items[0]) // todo - should be on server side
      // .do(data => console.log('server data:', data))  // debug
      .toPromise()
      .catch(e => this.handleError(e));
  }
  getUserActivities(userId: number): Promise<any[]> {
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      Authorization: this.tokenService.authorization
    });
    let requestOptions: RequestOptions = new RequestOptions({ headers });
    return this.http.get(
      `${serverApiUrl}/Backoffice/BorrowerActivities/${userId}`, requestOptions)
      .map((res: Response) => res.json())
      .map((json) => json.result.items)
      // .do(data => console.log('server data:', data))  // debug
      .catch(e => this.handleError(e))
      .toPromise();
  }
  /**
  * Handle HTTP error
  */
  private handleError(error: any) {
    if (error.status === 401) {
      this.router.navigate(['/session', 'signin']);
    }
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : error;
    console.error(errMsg); // log to console instead
    return Promise.reject(errMsg);
  }
}
