import { HttpErrorResponse, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable, catchError, throwError } from 'rxjs';

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

  constructor(private router: Router, private toastr: ToastrService) { }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 403) {
          this.toastr.error("Error", error.message, {
            timeOut: 3000,
            closeButton: true,
          });
          // this.router.navigate(['/error/error403']);
        } else if (error.status === 404) {
          this.toastr.error("Error", error.message, {
            timeOut: 3000,
            closeButton: true,
          });
          // this.router.navigate(['/error/error404']);
        } else if (error.status === 500) {
          this.toastr.error("Error", error.message, {
            timeOut: 3000,
            closeButton: true,
          });
          // this.router.navigate(['/error/error500']);
        } else if (error.status === 502) {
          this.toastr.error("Error", error.message, {
            timeOut: 3000,
            closeButton: true,
          });
          // this.router.navigate(['/error/error500']);
        }
        return throwError(error);
      })
    );
  }
}
