import { Injectable } from '@angular/core';
import { HttpHandler, HttpRequest, HttpInterceptor, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../../services/auth.service';
import { SessionService } from '../../services/session.service';

@Injectable()
export class BearerInterceptor implements HttpInterceptor {

  constructor(
    private readonly sessionService: SessionService,
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


    // this.logger.level = LogLevel[this.appConfig.getLogLevel()];
    // this.logger.debug('at BearerInterceptor...');

    if (
      /^(http|https):/i.test(request.url) &&
      request.url.toLowerCase().indexOf("\/assets") === -1 &&
      request.url.toLowerCase().indexOf("assets\/") === -1 &&
      request.url.toLowerCase().indexOf("\/maps.googleapis.com\/") === -1
    ) {
      if (
        request.url.toLowerCase().indexOf("\/token\/create") === -1 &&
        request.url.toLowerCase().indexOf("\/token\/validate") === -1 &&
        request.url.toLowerCase().indexOf("\/account\/forgotpassword") === -1
      ) {

        request = request.clone({
          headers: request.headers
            .set("accessToken", `${this.sessionService.loginUserToken}`)
        });
      }
    }

    return next.handle(request);
  }
}