import { Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Utils } from '../shares';
import {AuthenticationService} from '../user-services/authentication.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard  {
  msg ="[AuthGuard] ";
  constructor(private router: Router,
    private authService :AuthenticationService ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const roleAllowed = route.data['roleAllowed'];
    const user = Utils.getCurrentUser();   
    const userRole = Utils.getUserRole(user);
    let hasLoggedIn = Utils.getIsAuth();   
    //console.log(this.msg + " the userlogin ", user, hasLoggedIn);
    if (hasLoggedIn) {

      if (roleAllowed != undefined)
      {
        //it number toString
      // console.log("[auth-guard] ther roleAllow ", roleAllowed);
     // console.log("[auth-guard] before roleAllow ", roleAllowed,userRole);
        if (roleAllowed.indexOf(userRole.toString()) != -1) {       
         // console.log("[auth-guard] pass roleAllow ", roleAllowed,userRole);
          return true;
        }
        else {
          this.authService.logout();
          this.router.navigate(['/login']);
          return false;
        }
      }
      else //if no role define just return hasLoggedIn
      {
        return hasLoggedIn;
      }
    }
    else
    {
     // this.authService.logout();
      this.router.navigate(['/login']);
      return false;
    }

    // not logged in so redirect to login page with the return url
    //this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    this.authService.logout();
    return false;
  }
 
}
