import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { USERInterface } from '../interfaces/user-interface';
import { ENCService } from '../services/enc/enc.service';
import { IAMService } from '../services/iam/iam.service';
import * as sodium from 'libsodium-wrappers';


@Injectable({
  providedIn: 'root',
})
export class AdminGuard implements CanActivate {
  
  constructor(private _iamService: IAMService, private router: Router, private _encService:ENCService) {}

  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
   
  ):
    Promise<boolean> {

    let usuario:USERInterface = JSON.parse(localStorage.getItem('TIMUSERENC')!)
    
    const sleep = (ms:number) => new Promise(resolve => setTimeout(resolve, ms))
    await sleep(600);

    if (usuario != null) {
      let perfil_des =  this._encService.desencriptar(usuario.PERFIL);
      switch (perfil_des) {
        case "Administrador":
          
          return true;
        case "Usuario":
          if(window.location.pathname == "/admin/mesmav"){
            this.router.navigate(['/mesmav']);
          }else{
            this.router.navigate(['/mesmpr']);
          }
          
          return false;
        default:
          this.router.navigate(['/iam']);
          return false;
      }
    } else {
      this.router.navigate(['/iam']);
      return false;
    } 

  }

}
