import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../services/authentication.service';
import { Location } from '@angular/common';


@Injectable()
export class DashboardGuard implements CanActivate {
  constructor(private router: Router,
              private auth:AuthenticationService,
              private location:Location) {}

  async canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot) {
    const fromLogin:boolean = route.queryParamMap.get("start")=="1";
    const loggedIn:boolean = fromLogin || await this.auth.refreshToken().toPromise()
    
    if(!loggedIn) {
      return this.logout();
    }

    /*if (this.auth.currentAuthStatus() == false) {
      return this.logout();
    }*/

    if(!this.auth.isRolePermitted()) {
      return this.logout();
    }

    return true;
  }

  private logout() {
    this.router.navigate(['/auth', 'login']);
    return false;
  }
}