import { Injectable, Injector, Inject, DOCUMENT } from '@angular/core';

import { AppConfig } from "./app.config";
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable } from 'rxjs';

@Injectable()
export class AccessTokenInterceptor implements HttpInterceptor {
  private oauthService: OAuthService = null;
  private audience: string[] = [];
  private base: string;

  constructor(private injector: Injector, private appConfig: AppConfig, @Inject(DOCUMENT) private document: any) {   
    this.base = document.location.href;
  }

  hasAudience(url: string): boolean {
    const u = new URL(url,this.base);
    for (const audience of this.audience) {
      if (u.href.startsWith(audience)) return true;
    }
    return false;
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.oauthService && this.hasAudience(request.url)) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.oauthService.getAccessToken()}`
        }
      });
    } else {
      this.oauthService = this.injector.get(OAuthService, null);
      if(this.oauthService && this.oauthService.issuer) this.audience = (this.appConfig.getConfig("audience") as string).split(",");
    }
    return next.handle(request);
  }
}

