import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Action, UserActionsResponse, UserTotalActionsResponse } from '../../../../interfaces/user-actions.interface';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { ResourcesService } from '../../../../services/resources.service';
import { FunctionsService } from '../../../../services/functions.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { ActionsService } from '../../../../services/actions.service';
import { MatDialog } from '@angular/material/dialog';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { ScriptDialogComponent } from './script-dialog/script-dialog.component';

@Component({
    selector: 'app-details',
    templateUrl: './details.component.html',
    styleUrl: './details.component.css',
    standalone: false
})
export class DetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string
  userName: string;
  idUserActions: string;
  totalActions: number;
  pageSize: number;
  pageIndex: number;
  orderColumn: string;
  orderDirection: string;
  actionsHistoryEnabled: boolean;

  actions: Action[];

  dataSource: MatTableDataSource<Action>;
  displayedColumns: string[] =  ['ID', 'MODULO', 'SUBMODULO', 'FUNCION', 'PANTALLA', 'TIPOACCION', 'FECHA', 'ACCIONES'];

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

  btnSmall: boolean = false;
  txtBuscador:string;

  constructor(
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _actionsService: ActionsService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _router: Router,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.userName = "";
    this.idUserActions = "";
    this.totalActions = 0;
    this.pageSize = 10;
    this.pageIndex = 0;
    this.orderColumn = 'FECHA';
    this.orderDirection = 'desc';
    this.actionsHistoryEnabled = true;
    this.dataSource = new MatTableDataSource();

    this.actions = [];
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let idUserActions = params['info'];
      if(idUserActions == null || idUserActions == undefined || idUserActions == ''){
        this._resourcesService.openSnackBar('No se envió la información requerida.');
        this.goBack(1);
      }else{
        this.idUserActions = idUserActions;
        this.getUserTotalActions();
      }
    });
    
    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 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}`);
        }
      }
    });
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async getUserTotalActions(){
    try{
      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.actionsHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P02HIAC')[0].access > 0;

      let idUser = localStorage.getItem('idusuario')!;
      let totalActions: UserTotalActionsResponse = await lastValueFrom(this._actionsService.getUserTotalActions(
        this.idUserActions,
        idUser,
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idUserActionsDec = await this._encService.decrypt(totalActions.response.IDUSUARIO);
        let userName = this._functionsService.buildName(
          totalActions.response.NOMBRE,
          totalActions.response.APEPAT,
          totalActions.response.APEMAT
        );

        this.userName = `${userName} (${idUserActionsDec})`;
        this.totalActions = totalActions.response.TOTAL_ACCIONES;

        let offset = this.pageIndex * this.pageSize;
        this.getUserActions(offset, this.pageSize);
      }
    }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;
    }
  }

  private async getUserActions(offset: number, limit: number){
    try{
      this.dataSource = new MatTableDataSource();

      let idUser = localStorage.getItem('idusuario')!;
      let userActions: UserActionsResponse = await lastValueFrom(this._actionsService.getUserActions(
        this.idUserActions,
        offset,
        limit,
        this.orderColumn,
        this.orderDirection,
        idUser,
        1,
      ));
      console.log(userActions);

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

      if(!this.hasError){
        let userActionsArr: Action[] = [];
        for(const action of userActions.response){
          action.ID_ACCION = await this._encService.decrypt(action.ID_ACCION);

          if(action.MODULO != null){
            action.MODULO = await this._encService.decrypt(action.MODULO);
          }

          if(action.SUBMODULO != null){
            action.SUBMODULO = await this._encService.decrypt(action.SUBMODULO);
          }

          if(action.FUNCION != null){
            action.FUNCION = await this._encService.decrypt(action.FUNCION);
          }

          if(action.PANTALLA != null){
            action.PANTALLA = await this._encService.decrypt(action.PANTALLA);
          }

          userActionsArr.push(action);
        }
        
        this.dataSource = new MatTableDataSource(userActionsArr);
      }
      
      this.isLoading = false;
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;
      
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

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

  handlePageEvent(e: PageEvent){
    this.pageIndex = e.pageIndex;
    this.pageSize = e.pageSize;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.getUserTotalActions();
  }

  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();
    }
  }

  sortData(sort: any){
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    if(sort.direction == ''){
      this.orderColumn = 'FECHA';
      this.orderDirection = 'desc';
    }else{
      this.orderColumn = sort.active;
      this.orderDirection = sort.direction;
    }

    this.getUserTotalActions();
  }

  openDescription(desc: string){
    this._dialog.open(ScriptDialogComponent, {
      data: {
        desc: desc
      }
    })
  }
}
