import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {from, Observable} from "rxjs";
import {TokenProvider} from "../provider/token.provider";
import {Injectable} from "@angular/core";
import {switchMap} from "rxjs/operators";

@Injectable({providedIn: 'root'})
export class TokenInterceptor implements HttpInterceptor {
  constructor(protected tokenProvider: TokenProvider) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.tokenProvider.getToken()).pipe(
        switchMap(token => {
          const modifiedRequest = request.clone({
                                                  setHeaders: {Authorization: `Bearer ${token}`}
                                                });
          return next.handle(modifiedRequest);
        })
    );
  }
}