import { LocationStrategy } from '@angular/common';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../../services/authenticate.service';
import { I18NService } from '../../services/i18n.service';
import { ErrorMessages, FormConstants } from '../../utils/enums';
import { CredentialService } from '../../services/credential.service';


@Injectable(
    { providedIn: 'root' }
)
export class ActivityGuard implements CanActivate {

    constructor(private router: Router, private authService: AuthenticationService, private i18nService: I18NService, private credentialService: CredentialService) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (typeof window !== 'undefined' && window.localStorage) {
            let permissions = JSON.parse(window.localStorage.getItem('permission') || '[]');
            if (this.authService.isAuthenticated()) {  
                if (this.authService.isAdminUser()){
                    return true;
                }
                let routeLink = (state.url.split('?'))[0];
                if (this.isRouteAuthorized(routeLink, route.queryParams, permissions)) {
                    return true;
                }
                this.i18nService.error(ErrorMessages.ACCESS_DENIED, []);
                window.localStorage.setItem('currentSubModule','dashboard');
                this.router.navigate(["/home/dashboard"]);
                return false;
            } else {
                this.authService.logout();
                return false;
            }
        }
        return false;
    }

    isRouteAuthorized(routerLink: string, queryParams: any, permissions: any): boolean {
        let routePermissions : any = {}
        let permissionName : any = {}
        permissions.forEach((permission: any) => {
            routePermissions[permission.route] = permission.checked;
            permissionName[permission.name] = permission.checked;
            if(permission.children.length>0){
              permission.children.forEach((child: any)=>{
                routePermissions[child.route] = child.checked;
                permissionName[child.name] = child.checked;
              })
            }
          });
        if(routePermissions[routerLink]){
            return true;
        }
        return false;
    }

}