import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { environment } from '@environments/environment';
import { User } from '@app/models';
import { Observable } from 'rxjs/internal/Observable';
import { throwError } from 'rxjs/internal/observable/throwError';
import { map, catchError } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private http: HttpClient) { }

  getAllUsers() {
      return this.http.get<User[]>(`${environment.productionApiUrl}/users`);
  }


  createUser(user: { first_name :string, last_name :string, 
    email :string, role :number, organizations?: any }): Observable<boolean> {
      return this.http.post<any>(`${environment.productionApiUrl}/users`, user)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      )  
  }

  validateUserToken(user: {token :string}): Observable<boolean> {
      return this.http.post<any>(`${environment.productionApiUrl}/user/tokenvalidation`, user)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      )  
  }
  
  activateUser(user: { first_name :string, last_name :string, 
    email :string, password: string, confirm_password :string }): Observable<boolean> {
      return this.http.post<any>(`${environment.productionApiUrl}/user/activate`, user)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      )  
  }


  errorHandl(error) {
    let errorMessage = '';
    if(error.error) {
      // Get client-side error
      errorMessage = error.error;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
 }

}
