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

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

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.handle(request, next))
  }

  private async handle(request: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
      const token = await this.tokenProvider.getToken();
      request = request.clone({
          setHeaders: { Authorization: `Bearer ${token}` }
      });
      return next.handle(request).toPromise();
  }
}