import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
import { KeycloakInitializerService } from '../services/keycloak-initializer.service';
import { createLogger } from '../utils/utils';
const logger = createLogger('AuthGuard');
@Injectable({
  providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
  constructor(protected override readonly router: Router, protected readonly keycloak: KeycloakService, private keycloakInitializer: KeycloakInitializerService) {
    super(router, keycloak);
  }

  async isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
    logger.info(`--->AuthGuard`);
    while (!this.keycloakInitializer.initialized) {
      logger.info(`Waiting 100 msec`);
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    // Force the user to log in if currently unauthenticated.
    const authenticated = this.keycloak.isLoggedIn();
    //this.keycloak.isTokenExpired()
    if (!this.authenticated && !authenticated) {
      await this.keycloak.login({
        redirectUri: window.location.origin + state.url,
      });
      // return false;
    }

    // Get the roles required from the route.
    const requiredRoles = route.data['roles'];

    // Allow the user to proceed if no additional roles are required to access the route.
    if (!Array.isArray(requiredRoles) || requiredRoles.length === 0) {
      return true;
    }

    // Allow the user to proceed if all the required roles are present.
    return requiredRoles.every(role => this.roles.includes(role));
  }
}
