import { Injectable } from "@angular/core";

import { of as observableOf, Observable, throwError } from "rxjs";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { retry, catchError, map, timeout } from "rxjs/operators";

import { environment } from "@environments/environment";

@Injectable({
  providedIn: "root"
})
export class InvestmentsService {
  time: number = 6000;

  constructor(private http: HttpClient) {}

  // Obtener listado de propuestas de inversiones
  getProposalInvestmentsList() {
    return this.http
      .get<any>(`${environment.productionApiUrl}/inversiones`, {})
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  // Obtener propuesta de inversion segun ID
  getProposalInvestment(id: string) {
    return this.http
      .get<any>(`${environment.productionApiUrl}/inversion/${id}`)
      .pipe(
        timeout(this.time),
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  createProposalInvestment(inversion: Object): Observable<boolean> {
    return this.http
      .post<any>(`${environment.productionApiUrl}/inversion`, inversion)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  updateProposalInvestment(id: string, inversion: Object): Observable<boolean> {
    return this.http
      .put<any>(`${environment.productionApiUrl}/inversion/${id}`, inversion)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  sendReviewProposalInvestment(inversion: Object): Observable<boolean> {
    return this.http
      .post<any>(`${environment.productionApiUrl}/auditoria`, inversion)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  sendProposalInvestmentToNextStep(inversion: Object): Observable<boolean> {
    return this.http
      .post<any>(`${environment.productionApiUrl}/auditoria`, inversion)
      .pipe(
        map(response => {
          return response;
        }),
        catchError(this.errorHandl)
      );
  }

  //if(error.error instanceof ErrorEvent) {
  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);
  }
}
