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';
import { NotificationsComponent } from '../notifications/notifications.component';

const REG_URL_LOGIN = /^https?:\/\/.*(:\d{1,5})?\/api\/account\/login$/;

@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']);
				if (!err.url.match(REG_URL_LOGIN)) {
					window.setTimeout(() => NotificationsComponent.error('Veuillez vous authentifier pour réaliser cette action.'), 500);
				}
			}

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