import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { ModulesService } from '../../../../services/modules.service';
import { ResourcesService } from '../../../../services/resources.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { FunctionsService } from '../../../../services/functions.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { SubmoduleFunctionsResponse } from '../../../../interfaces/submodule-functions.interface';
import { Permissions, PermissionsInterface } from '../../../../interfaces/permissions.interface';

@Component({
    selector: 'app-submodule-functions',
    templateUrl: './submodule-functions.component.html',
    styleUrl: './submodule-functions.component.css',
    standalone: false
})
export class SubmoduleFunctionsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  functions: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _modulesService: ModulesService,
    private _socketService: SocketService,
    private _resourcesService: ResourcesService,
    private _usersProfilesService: UsersProfilesService,
    private _router: Router,
    private _functionsService: FunctionsService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.functions = [];
  }

  ngOnInit(): void {
    this.openMenu(this._data.module, this._data.submodule);
    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 == this._data.module);
            if(modPerm.length > 0){
              let modEnc = await this._encService.encrypt(this._data.module);
              let subEnc = await this._encService.encrypt(this._data.submodule);
              let subPerm = modPerm[0].children.filter(item => item.id == this._data.submodule);
              let submoduleFunctions: SubmoduleFunctionsResponse = await lastValueFrom(this._modulesService.getSubmoduleFunctions(
                modEnc,
                subEnc,
                idUser,
                1
              ));

              if(submoduleFunctions.error){
                this._resourcesService.openSnackBar(submoduleFunctions.msg);
              }else if(subPerm.length > 0){
                this.functions = [];
                for(const funct of submoduleFunctions.response){
                  let permFun = subPerm[0].children.filter(item => item.id == funct.IDFUNCION);
                  if(permFun.length > 0){
                    if(funct.HASSCREENS && permFun[0].access > 0){
                      this.functions.push(funct);
                    }
                  }
                }
              }
            }
          }
        }
      }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 openMenu(module: string, submodule: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let modEnc = await this._encService.encrypt(module);
      let subEnc = await this._encService.encrypt(submodule);

      let submoduleFunctions: SubmoduleFunctionsResponse = await lastValueFrom(this._modulesService.getSubmoduleFunctions(
        modEnc,
        subEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = '';
        if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
          permissionsDec = '[]';
        }else{
          permissionsDec = await this._encService.decrypt(permissionsEnc!);
        }

        let permissionsArr: Permissions = JSON.parse(permissionsDec);
        let permMod: PermissionsInterface[] = [];
        if(permissionsArr.permissions == undefined){
          permMod = [];
        }else{
          permMod = permissionsArr.permissions.filter(item => item.id == module);
        }

        if(permMod.length > 0){
          let permSub = permMod[0].children.filter(item => item.id == submodule);
          if(permSub.length > 0){
            for(const funct of submoduleFunctions.response){
              let permFun = permSub[0].children.filter(item => item.id == funct.IDFUNCION);
              if(permFun.length > 0){
                if(funct.HASSCREENS && permFun[0].access > 0){
                  this.functions.push(funct);
                }
              }
            }
          }
        }
      }

      this.isLoading = false;
    }catch(error: any){
      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;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }
}
