import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { UtilsService } from '../services/utils.service';
import { environment } from 'src/environments/environment';
import { TokenService } from '../services/token.service';

@Injectable({
    providedIn: 'root'
})
export class ApiInterceptor implements HttpInterceptor {
  constructor(private utilsService:UtilsService,
              private token:TokenService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const tractable:boolean = (request.url.indexOf(environment.baseApiUrl) != -1) && request.url.indexOf("auth")==-1;

    //tractem request
    if(tractable) {
        this.utilsService.enableLoading();
    }

    //tractem response
    return next.handle(request).pipe(
        catchError((error:HttpErrorResponse) => {
            if(tractable) {
                this.utilsService.disableLoading();
                let title:string;
                switch(request.method) {
                    case 'GET':
                        title = "Error obteniendo datos...";
                        break;
                    case 'POST':
                        title = "Error creando...";
                        break;
                    case 'PUT':
                        title = "Error actualizando...";
                        break;
                    case 'DELETE':
                        title = "Error borrando...";
                        break;
                    default:
                        title = "Error";
                        break;
                }
                const message = error.error ? (`Error ${error.status}: ${error.error.error ? error.error.error : error.error.message}`) : (`Error ${error.status}: ${error.message}`)
                this.utilsService.showMessage("error", title, message);
            }
            return throwError(error);
        }),
        map((event:HttpEvent<any>) => {
            if(event instanceof HttpResponse && tractable) {
                this.utilsService.disableLoading();
                switch (request.method) {
                    case "POST":
                        this.utilsService.showMessage("success", "Se ha creado correctamente.");
                        break;
                    case "PUT":
                        this.utilsService.showMessage("success", "Se ha actualizado correctamente");
                        break;
                    case "DELETE":
                        this.utilsService.showMessage("success", "Se ha borrado correctamente");
                        break;
                }
            }
            return event;
        })
    );
  }
}