import { Component, OnInit } from '@angular/core';
import { Submodules } from '../../interfaces/submodules.interface';
import { ModuleFunction, ModuleFunctionsResponse } from '../../interfaces/module-functions.interface';
import { ModulesService } from '../../services/modules.service';
import { EncService } from '../../services/enc.service';
import { Router } from '@angular/router';
import { SocketService } from '../../services/socket.service';
import { UsersProfilesService } from '../../services/users-profiles.service';
import { ResourcesService } from '../../services/resources.service';
import { FunctionsService } from '../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { UserConsultResponse } from '../../interfaces/user.interface';
import { ProfileInterface } from '../../interfaces/profile.interface';
import { Permissions } from '../../interfaces/permissions.interface';

@Component({
    selector: 'app-system-admin',
    templateUrl: './system-admin.component.html',
    styleUrl: './system-admin.component.css',
    standalone: false
})
export class SystemAdminComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  submodules: Submodules[];
  functions: ModuleFunction[];
  functionsAux: ModuleFunction[];

  constructor(
    private _modulesService: ModulesService,
    private _encService: EncService,
    private _router: Router,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.submodules = [];
    this.functions = [];
    this.functionsAux = [];
  }

  ngOnInit(): void {
    this.getSubmodules();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let newFunct: ModuleFunction[] = [];
              for(let item of this.functionsAux){
                let idFunc = item.IDFUNCION;
                let func = modPerm[0].children.filter(item2 => item2.id == idFunc);

                if(func.length > 0){
                  if(func[0].access > 0){
                    newFunct.push(item);
                  }
                }
              }

              this.functions = newFunct;
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

  async getSubmodules(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.decrypt(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);
      let permMod = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];

      let modEnc = await this._encService.encrypt('S002V01M01ADSI');
      let idEnc = localStorage.getItem('idusuario')!;

      let functions: ModuleFunctionsResponse = await lastValueFrom(this._modulesService.getModuleFunctions(
        modEnc, 
        idEnc, 
        1
      ));

      this.hasError = functions.error;
      this.errorStr = functions.msg;

      if(!this.hasError){
        functions.response.forEach(item => {
          let idFunc = item.IDFUNCION;
          let func = permMod.children.filter(item2 => idFunc == item2.id)[0];
          if(func.access > 0){
            this.functions.push(item);
          }
        });

        this.functionsAux = functions.response;
      }

      this.isLoading = false;
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;

      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

  openFunction(funcID: string){
    let route = funcID.substring(10, funcID.length);
    this._router.navigate([`sam/ADSI/${route}`]);
  }
}
