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) {}

  changePassword(user: {
    old_password: string;
    new_password: string;
    confirm_new_password: string;
  }): Observable<boolean> {
    return this.http
      .put<any>(`${environment.productionApiUrl}/change-password`, 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);
  }
}
