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 {
  public aux_test: any;

  constructor( private router: Router, private _encService:ENCService) {}
  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
   
  ):Promise<boolean> {
    let rfc_local = localStorage.getItem('RFCEMPRESA')!;
    let user_local = localStorage.getItem('TIMUSERENC')!;
    this.aux_test = setInterval(() => {
      let jwt_local = localStorage.getItem('jwt');      
      if (jwt_local !== null ) {
        localStorage.setItem('RFCEMPRESA', rfc_local);
        localStorage.setItem('TIMUSERENC', user_local);
      }
    }, 1000);
    

    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);

      if(perfil_des === "1"){
        return true;
      }else{
        if(window.location.pathname == "/admin/mesmav"){
          this.router.navigate(['/mesmav']);
        }else{
          this.router.navigate(['/mesmpr']);
        }
        return false;
      }
    } else {      
      this.router.navigate(['/iam']);
      return false;
    }
  }

}
