import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
import { OidcAuthService } from '../service/oidc/oidc.service';
import { AppTokenService } from '../service/security/app-token.service';
import { Router } from '@angular/router';
import { NgProgress } from 'ngx-progressbar';
// import { NgProgress } from 'ngx-progressbar';
// import { AppTokenService } from '../service/security/app-token.service';

@Injectable()
export class TokenIntercepterInterceptor implements HttpInterceptor {

  constructor( private odicOpenService: OidcAuthService,
    public appTokenService : AppTokenService,
    private router: Router,
    private progress: NgProgress
    ) {

  }


  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const customReq = request.clone({
      setHeaders:{
          Authorization: request.url.includes('app_tokens') ?  this.odicOpenService.getAuthorizationHeaderValue() : `Bearer ${this.appTokenService.getToken()}`
      }
    })

    this.progress.ref('home-progress').start()
    return next.handle(customReq).pipe(
      finalize(() => this.progress.ref('home-progress').complete())
    );
  }
}
