import {Injectable} from '@angular/core';
import {
    CanActivate,
    ActivatedRouteSnapshot,
    RouterStateSnapshot, Router,
} from '@angular/router';
import {NgxPermissionsService} from "ngx-permissions";
import { AuthService } from '../_services';

@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router, private pService: NgxPermissionsService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        let user = this.authService.getUser();
        if(user){
            let permissions = this.authService.getPermission();
            let result = [];
            for(let i in permissions){
                if(permissions[i]){
                    result.push(i);
                }
            }
            this.pService.loadPermissions(result);
        }

        if(!user){
            this.router.navigateByUrl('/auth/login');
        }

        return !!user;
    }
}
