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 usuario:USERInterface = JSON.parse(localStorage.getItem('TIMUSERENC')!);
    if (usuario != null) {
      let perfil_des:string = "";
      await this._encService.desencriptar2(usuario.PERFIL.toString()).then(
        (data:string) => perfil_des = data,
        (error:any) => console.log(error)
      );

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

}
