import { ActivatedRouteSnapshot, CanActivateFn, RouterStateSnapshot } from '@angular/router';
import { ResourcesService } from '../services/resources/resources.service';
import { inject } from '@angular/core';
import { EncService } from '../services/enc/enc.service';
import { PermissionsData } from '../components/acquisition-management/acquisition-management.component';

export const permissionGuard: CanActivateFn = async (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {

  const resourcesService:ResourcesService = inject(ResourcesService);
  const encService:EncService = inject(EncService);
  const arrComponentNotModules: Array<string> = ['home'];
  const location: string = state.url;

  let arrLocation: Array<string> = location.split('/');
  if (arrLocation.length === 0) {
    resourcesService.openSnackBar(`Ocurrió un error al obtener la información de la URL.`);
    return false;
  }
  arrLocation.shift();

  if (arrLocation.length === 1) {
    const app:string = arrLocation[0];
    if (app !== 'sam') {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el dato 'sam`);
      return false;
    }
  }

  if (arrLocation.length === 2) {
    const app:string = arrLocation[0];
    const idModule:string = arrLocation[1];

    if (app !== 'sam') {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el dato 'sam'.`);
      return false;
    }

    if (arrComponentNotModules.includes(idModule)) {
      return true;
    }
    let encPermissions = localStorage.getItem('permisos');
    if (encPermissions === null || encPermissions === undefined || encPermissions === '') {
      resourcesService.openSnackBar(`Ocurrió un error al obtener los permisos del usuario.`);
      return false;
    }
    const strPermissions:string = await encService.decrypt(encPermissions);
    const arrPermissions:Array<PermissionsData> = JSON.parse(strPermissions).permissions;
    let arrModulePermission = arrPermissions.find((permission:PermissionsData) => permission.id.substring(permission.id.length - 4, permission.id.length) === idModule);
    if (arrModulePermission === null || arrModulePermission === undefined) {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el módulo al que quiere acceder.`);
      return false;
    }
    if (arrModulePermission.access === 0) {
      resourcesService.openSnackBar(`No tienes los permisos necesarios para acceder al módulo.`);
      return false;
    }
    
  }

  if (arrLocation.length > 2) {
    
    const app:string = arrLocation[0];
    const idModule:string = arrLocation[1];
    const idSubmodule:string = arrLocation[2];
    let idFunction:string = '';
    if (3 in arrLocation) {
      idFunction = arrLocation[3];
    }

    if (app !== 'sam') {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el dato 'sam'.`);
      return false;
    }
    
    if (arrComponentNotModules.includes(idModule)) {
      return true;
    }

    let encPermissions = localStorage.getItem('permisos');
    if (encPermissions === null || encPermissions === undefined || encPermissions === '') {
      resourcesService.openSnackBar(`Ocurrió un error al obtener los permisos del usuario.`);
      return false;
    }
    const strPermissions:string = await encService.decrypt(encPermissions);
    const arrPermissions:Array<PermissionsData> = JSON.parse(strPermissions).permissions;
    
    let arrModulePermission = arrPermissions.find((permission:PermissionsData) => permission.id.substring(permission.id.length - 4, permission.id.length) === idModule);
    if (arrModulePermission === null || arrModulePermission === undefined) {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el módulo al que quiere acceder.`);
      return false;
    }
    if (arrModulePermission.access === 0) {
      resourcesService.openSnackBar(`No tienes los permisos necesarios para acceder al módulo.`);
      return false;
    }
    
    let arrSubmodulePermission = arrModulePermission.children.find((permission:PermissionsData) => permission.id.substring(permission.id.length - 4, permission.id.length) === idSubmodule);
    if (arrSubmodulePermission === null || arrSubmodulePermission === undefined) {
      resourcesService.openSnackBar(`Ocurrió un error al obtener el submódulo al que quiere acceder.`);
      return false;
    }
    if (arrSubmodulePermission.access === 0) {
      resourcesService.openSnackBar(`No tienes los permisos necesarios para acceder al submódulo.`);
      return false;
    }

    if (idFunction !== '') {
      let arrFunctionPermission = arrSubmodulePermission.children.find((permission:PermissionsData) => permission.id.substring(permission.id.length - 4, permission.id.length) === idFunction);
      if (arrFunctionPermission === null || arrFunctionPermission === undefined) {
        
        resourcesService.openSnackBar(`Ocurrió un error al obtener la función a la que quiere acceder.`);
        return false;
      }
      if (arrFunctionPermission.access === 0) {
        console.log(arrFunctionPermission);
        
        resourcesService.openSnackBar(`No tienes los permisos necesarios para acceder al esta función.`);
        return false;
      }
    }
  }
  
  return true;
};
