import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import {tap} from 'rxjs/operators';
import {Router} from '@angular/router';
import { AuthGuard } from '../services/auth.guard';

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

  constructor(private router: Router, private _auth: AuthGuard) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe( tap(() => {},
      (err: any) => {
        
      if (err instanceof HttpErrorResponse) {
        if (err.status !== 401) {
         return;
        }
        console.log("Interceptor error 401!!");
        this._auth.clearUser();
        this.router.navigate(['home']);
      }
    }));
  }
}