import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';
import { HttpCancelService } from '../services/http-cancel.service';

@Injectable()
export class AppInterceptor implements HttpInterceptor {
    constructor(private httpCancelService: HttpCancelService, private router: Router) {}

    intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return next.handle(req).pipe(
            takeUntil(this.httpCancelService.onCancelPendingRequests()),
            tap({
                next: () => {},
                error: (err) => {
                    if (err instanceof HttpErrorResponse) {
                        switch (err.status) {
                            case 404:
                                this.router.navigateByUrl('/error/404');
                                break;
                            case 500:
                                this.router.navigateByUrl('/error');
                                break;
                        }
                    }
                },
            }),
        );
    }
}
