import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { UberCacheService } from './uber-cache.service';

import { User } from './User';

@Injectable({
  providedIn: 'root'
})
export class ProfileService {

  constructor(
    private http: HttpClient,
    private uberCache: UberCacheService
  ) { }

  private requestCurrentUser(): Observable<User> {
    return this.http.get<UserResponse>('/api/v1/profile/me').pipe(catchError(this.handleError)).pipe(map((res: UserResponse) => res.user));
  }

  public currentUser(): Observable<User> {
    return this.uberCache.getRequest(this.requestCurrentUser.bind(this), `/api/v1/profile/events`, 'userUpdated');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // client or network error
      console.error('An error occurred:', error.error.message);
    } else {
      // backend returned an error
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`
      );
    }
    return throwError(
      `An eror occurred`
    );
  }
}

interface UserResponse {
  status: string;
  user: User
}
