import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';

import { Observable } from 'rxjs';
import { map, filter, tap } from 'rxjs/operators';

import { User } from '../entities';
import { AuthService } from '../services/auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.authService.getToken();

    let request: HttpRequest<any> = req;

    if (token) {
      request = req.clone({
        setHeaders: {
          token: token
        }
      });
    }

    return next.handle(request).pipe(
      tap(event => {
        // Do nothing for the interceptor
      }, (err: any) => {
        if (err instanceof HttpErrorResponse && err.status === 401) {
          this.authService.disconnect();
          this.router.navigate(['/login']);
        }
      })
    );
  }


}
