import { Injectable } from "@angular/core";
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from "@angular/common/http";
import { AuthService } from "@app/services/auth2.service";
import { Observable, throwError, BehaviorSubject } from "rxjs";
import { catchError, filter, take, switchMap } from "rxjs/operators";
import Swal from "sweetalert2";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  private isRefreshing = false;
  private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
    null
  );

  constructor(public authService: AuthService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (request.url.indexOf("token/refresh/") != -1) {
      request = this.addToken(request, this.authService.getRefreshToken());
    }
    //else if (request.url.indexOf("openweather")!= -1 ){
    //  request;
    //}
    else {
      if (this.authService.getJwtToken()) {
        request = this.addToken(request, this.authService.getJwtToken());
      }
    }

    return next.handle(request).pipe(
      catchError(error => {
        // Erase storage if response code from auth refresh gives 401 or 422 error
        if (
          request.url.indexOf("token/refresh/") != -1 &&
          error instanceof HttpErrorResponse
        ) {
          Swal.fire({
            allowOutsideClick: false,
            icon: "warning",
            title: "La sesión ha expirado",
            showConfirmButton: false
          });
          this.authService.removeTokens();
          setTimeout(function() {
            Swal.close();
            window.location.href = "#/login";
          }, 2000);
        }

        if (
          error instanceof HttpErrorResponse &&
          (error.status === 401 || error.status === 422)
        ) {
          return this.handle4xxError(request, next);
        } else {
          return throwError(error);
        }
      })
    );
  }

  private addToken(request: HttpRequest<any>, token: string) {
    return request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
  }

  // Cuando el endpoint devuelva 401 debe mandarlo al login y destruir las variables del storage
  private handle4xxError(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      return this.authService.refreshToken().pipe(
        switchMap((token: any) => {
          this.isRefreshing = false;
          this.refreshTokenSubject.next(token["token"]);
          return next.handle(this.addToken(request, token["token"]));
        })
      );
    } else {
      this.isRefreshing = false;

      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(2),
        switchMap(jwt => {
          return next.handle(this.addToken(request, jwt));
        })
      );
    }
  }
}
