import {Injectable} from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import {Observable} from "rxjs/index";
import {tap} from "rxjs/internal/operators";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('X-Authorization', localStorage.getItem('lifeToken') ? localStorage.getItem('lifeToken') : ''),
      setHeaders: {'Content-Type': 'application/json'}
    });
    return next.handle(authReq)
      .pipe(
        tap(
          event => {},
          error => {
            if (error.status === 401) {
              let {search, href} = window.location;
              href = href.replace(/&?t_reload=(\d+)/g, '');
              window.location.href = href + (search ? '&' : '?') + 't_reload=' + new Date().getTime();
            }

          }
        )
      );
  }
}
