import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { catchError, filter, switchMap, take, tap } from 'rxjs/operators';
import { AuthService } from './auth.service';
import { environment } from 'src/environments/environment';
import { TokenService } from './token.service';
const TOKEN_HEADER_KEY = 'Authorization';
@Injectable()
export class HttpRequestInterceptor {
  private isRefreshing = true;
  private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  constructor(private tokenService: TokenService, private authService: AuthService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.url.startsWith('/assets/')) {
      return next.handle(req);
    } else if (req.url.startsWith("./")) {
      return next.handle(req);
    } else {
      const portalUrl = req.url.includes("portal.myhr")
      const portalToken = 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBdXRoIiwidWlkIjoiOGFhNDUzMzAtMzE0Yy0xMWU3LWJhZjMtMmQ3ZDA5ODc3NzQ0Iiwicm9sZSI6InVzZXIiLCJpc3MiOiJDb21wdXRlciBTY2llbmNlIENvcnBvcmF0aW9uIExpbWl0ZWQiLCJmdWxsTmFtZSI6InRlZXJhZGFjaCBrdWhhdGFuYXNhdGllbiIsIm1lbWJlcklkIjoiOGFhNDUzMzAtMzE0Yy0xMWU3LWJhZjMtMmQ3ZDA5ODc3NzQ0In0.FO7u8g7KfzkmZFTuuniBCEQxduPjcvzMbH7iug3DT90'
      let authReq = req;
      const fullUrl = req.url.startsWith("http") ? req.url : environment.baseUrl + req.url;
      const token = portalUrl ? portalToken : this.tokenService.getToken()
      if (token != null && !req.url.includes("/refresh-token")) {
        authReq = this.addTokenHeader(req, "Bearer " + token, fullUrl);
      } else {
        const overideReq = {
          url: fullUrl,
        };
        authReq = req.clone(overideReq);
      }
      return next.handle(authReq).pipe(catchError(error => {
        if (fullUrl.includes("login")) {
          return next.handle(this.addTokenHeader(req, "Bearer ", fullUrl))
        } else if (error instanceof HttpErrorResponse && error.status === 401 && !fullUrl.includes("login")) {
          if (fullUrl.includes("/refresh-token") && error.status === 401) {
            this.tokenService.signOut();
          } else {
            this.isRefreshing = false;
            return this.handle401Error(authReq, next, fullUrl);
          }
        }
        return throwError(error);
      }));
    }
  }

  private handle401Error(request: HttpRequest<any>, next: HttpHandler, fullUrl: string) {
    if (!this.isRefreshing) {
      this.refreshTokenSubject.next(null);
      const token = this.tokenService.getRefreshToken();

      if (token) {
        return this.authService.refreshToken(token.replace("Bearer ", "")).pipe(
          switchMap((token: any) => {
            this.isRefreshing = true;
            this.refreshTokenSubject.next(token.accessToken);
            return next.handle(this.addTokenHeader(request, "Bearer " + token.accessToken, fullUrl));
          }),
          catchError((err) => {
            this.isRefreshing = false;
            this.tokenService.signOut();
            return throwError(err);
          })
        );
      } else {
        this.isRefreshing = false;
        this.tokenService.signOut();
        return throwError('No refresh token available');
      }
    }

    return this.refreshTokenSubject.pipe(
      filter(token => token !== null),
      take(1),
      switchMap((token) => next.handle(this.addTokenHeader(request, "Bearer " + token, fullUrl)))
    );
  }

  private addTokenHeader(request: HttpRequest<any>, token: string, fullUrl: string) {
    /* for Spring Boot back-end */
    // return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });

    /* for Node.js Express back-end */
    return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, token), url: fullUrl });
  }
}
