import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
	constructor(
		private router: Router,
		private authService: AuthService
	) {}

	intercept(pRequest: HttpRequest<any>, pNext: HttpHandler): Observable<HttpEvent<any>> {
		return pNext.handle(pRequest).pipe(catchError(err => {
			if (err.status === 401) {
				this.authService.setAnonymous();
				this.router.navigate(['/login']);
			}

			const error = err.error.message || err.statusText;
			return throwError(error);
		}));
	}
}
