import { Component, OnInit, ViewChild } from '@angular/core';
import { MenuModule, MenuResponse } from '../../../interfaces/menu.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ActionsService } from '../../../services/actions.service';
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 { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { ActionsResponse } from '../../../interfaces/actions.interface';
import { Permissions } from '../../../interfaces/permissions.interface';

interface UserAction{
  ID: string,
  NOMBRE: string,
  MODULO: string,
  SUBMODULO: string,
  FUNCION: string,
  PANTALLA: string,
  TIPACC: string,
  FECAC: string,
}
@Component({
    selector: 'app-actions',
    templateUrl: './actions.component.html',
    styleUrl: './actions.component.css',
    standalone: false
})
export class ActionsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  userActions: UserAction[];
  modulesArr: MenuModule[];
  actionsMonitoringEnabled: boolean;
  actionsHistoryEnabled: boolean;
  
  dataSource?: MatTableDataSource<UserAction>;
  displayedColumns: string[] =  ['ID', 'NOMBRE', 'MODULO', 'SUBMODULO', 'FUNCION', 'PANTALLA', 'TIPACC', 'FECAC', 'ACCIONES'];

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  btnSmall: boolean = false;
  txtBuscador:string;

  constructor(
    private _actionsService: ActionsService,
    private _modulesService: ModulesService,
    private _encService: EncService,
    private _router: Router,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.hasError = false;
    this.isLoading = true;
    this.errorStr = "";
    this.userActions = [];
    this.modulesArr = [];
    this.txtBuscador = '';
    this.actionsMonitoringEnabled = true;
    this.actionsHistoryEnabled = true;
  }

  ngOnInit(): void {
    this.getData();

    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 funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F02SAUS');
              if(funPerm.length > 0){
                let actionsMonitoringEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01MOAC');
                if(actionsMonitoringEnabled.length > 0){
                  this.actionsMonitoringEnabled = actionsMonitoringEnabled[0].access > 0;
                }

                let actionsHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02HIAC');
                if(actionsHistoryEnabled.length > 0){
                  this.actionsHistoryEnabled = actionsHistoryEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }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 getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      this.userActions = [];
      
      //Se consulta el menú de módulos y sus hijos para evitar demasiadas peticiones
      let idUser = localStorage.getItem('idusuario')!;
      let idUserDec = await this._encService.decrypt(idUser);
      let menu: MenuResponse = await lastValueFrom(this._modulesService.getMenu(idUser, 1));

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

      if(!this.hasError){
        let actions: ActionsResponse = await lastValueFrom(this._actionsService.getLastActions(idUser, 1));

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

        if(!this.hasError){
          let menuDec: MenuModule[] = [];
          for(const module of menu.response){
            module.ID_MODULO = await this._encService.decrypt(module.ID_MODULO);

            for(const submodule of module.SUBMODULES){
              submodule.IDSUBMODULO = await this._encService.decrypt(submodule.IDSUBMODULO);

              for(const func of submodule.FUNCIONES){
                func.IDFUNCION = await this._encService.decrypt(func.IDFUNCION);

                for(const screen of func.PANTALLAS){
                  screen.IDPANTALLA = await this._encService.decrypt(screen.IDPANTALLA);
                }
              }
            }

            for(const func of module.MENUS){
              func.IDFUNCION = await this._encService.decrypt(func.IDFUNCION);

              for(const screen of func.PANTALLAS){
                screen.IDPANTALLA = await this._encService.decrypt(screen.IDPANTALLA);
              }
            }
            
            menuDec.push(module);
          }

          this.modulesArr = menuDec;
          for(const action of actions.response){
            let completeName = this._functionsService.buildName(action.NOMBRE, action.APEPAT, action.APEMAT);
            let idModuleDec = action.IDMODULO == null ? '-' : await this._encService.decrypt(action.IDMODULO);
            let moduleFilt = this.modulesArr.filter(item => item.ID_MODULO == idModuleDec);
            let date = action.FECHAACCION == null ? '-' : this._functionsService.orderDate(action.FECHAACCION);

            let actionReg: UserAction = {
              ID: await this._encService.decrypt(action.IDUSUARIO),
              NOMBRE: completeName,
              MODULO: '-',
              SUBMODULO: '-',
              FUNCION: '-',
              PANTALLA: '-',
              TIPACC: action.TIPOACCION == null ? '-' : action.TIPOACCION,
              FECAC: date,
            }

            if(moduleFilt.length > 0){
              actionReg.MODULO = moduleFilt[0].NOMBRE_MODULO;

              let idSubmoduleDec = action.IDSUBMODULO == null ? '-' : await this._encService.decrypt(action.IDSUBMODULO);
              let submoduleFilt = moduleFilt[0].SUBMODULES.filter(item => item.IDSUBMODULO == idSubmoduleDec);

              if(submoduleFilt.length > 0){
                actionReg.SUBMODULO = submoduleFilt[0].NOMBRESUBMODULO;

                let idFunctionDec = action.IDFUNCION == null ? '-' : await this._encService.decrypt(action.IDFUNCION);
                let functionFilt = submoduleFilt[0].FUNCIONES.filter(item => item.IDFUNCION == idFunctionDec);

                if(functionFilt.length > 0){
                  actionReg.FUNCION = functionFilt[0].NOMBREFUNCION;

                  let idScreenDec = action.IDPANTALLA == null ? '-' : await this._encService.decrypt(action.IDPANTALLA);
                  let screenFilt = functionFilt[0].PANTALLAS.filter(item => item.IDPANTALLA == idScreenDec);

                  if(screenFilt.length > 0){
                    actionReg.PANTALLA = screenFilt[0].NOMBREPANTALLA;
                  }
                }
              }

              let idFunctionDec = action.IDFUNCION == null ? '-' : await this._encService.decrypt(action.IDFUNCION);
              let functionFilt = moduleFilt[0].MENUS.filter(item => item.IDFUNCION == idFunctionDec);

              if(functionFilt.length > 0){
                actionReg.FUNCION = functionFilt[0].NOMBREFUNCION;

                let idScreenDec = action.IDPANTALLA == null ? '-' : await this._encService.decrypt(action.IDPANTALLA);
                let screenFilt = functionFilt[0].PANTALLAS.filter(item => item.IDPANTALLA == idScreenDec);

                if(screenFilt.length > 0){
                  actionReg.PANTALLA = screenFilt[0].NOMBREPANTALLA;
                }
              }
            }

            if(idUserDec != actionReg.ID){
              this.userActions.push(actionReg);
            }
          }

          let permissionsEnc = localStorage.getItem('permisos');
          let permissionsDec = await this._encService.decrypt(permissionsEnc!);
          let permissionsArr: Permissions = JSON.parse(permissionsDec);

          let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
          let funPerm = modPerm.children.filter(item => item.id == 'S002V01F02SAUS')[0];

          this.actionsMonitoringEnabled = funPerm.children.filter(item => item.id == 'S002V01P01MOAC')[0].access > 0;
          this.actionsHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P02HIAC')[0].access > 0;
          
          this.dataSource = new MatTableDataSource(this.userActions);
          this.dataSource.paginator = this.paginator!;
          this.dataSource.sort = this.sort!;
        }
      }

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

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  async openActions(id: string){
    let idEnc = await this._encService.encrypt(id);
    this._router.navigate(['sam/ADSI/SAUS/detalles'], {
      queryParams: {
        info: idEnc
      }
    });
  }
}
