import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest, HttpResponse
} from "@angular/common/http";
import {
  HttpSecurityErrorInterceptor,
  MessagesService,
  UserService
} from "@webbpm/base-package";
import {Injectable} from "@angular/core";
import {Router} from "@angular/router";
import {from, Observable} from "rxjs";
import {catchError, map} from "rxjs/operators";
import {AuthenticationService} from "../../security/authentication.service";

@Injectable()
export class ErvuHttpSecurityErrorInterceptor extends HttpSecurityErrorInterceptor
    implements HttpInterceptor {
  private authService: AuthenticationService;


  constructor(router: Router, messagesService: MessagesService, userService: UserService,
              authService: AuthenticationService) {
    super(router, messagesService, userService);
    this.authService = authService;
  }

  protected processAuthError(req: HttpRequest<any>, next: HttpHandler,
                             error: any): Observable<HttpEvent<any>> {
    if (this.authService.isAuthenticated()) {
      return super.processAuthError(req, next, error);
    }
    else {
      return from(this.authService.redirectToEsia()).pipe(
          map(() => new HttpResponse<any>()),
          catchError((err) => {
            throw err;
          })
      );
    }
  }
}
