import { FunctionsService } from './../../../services/functions.service';
import { MenuModule } from './../../../interfaces/menu.interface';
import { MenuResponse } from 'src/app/interfaces/menu.interface';
import { ModulesService } from 'src/app/services/modules.service';
import { Router } from '@angular/router';
import { EncService } from './../../../services/enc/enc.service';
import { ActionsResponse } from './../../../interfaces/actions.interface';
import { lastValueFrom } from 'rxjs';
import { ActionsServiceService } from './../../../services/actions-service.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

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',
  styleUrls: ['./actions.component.css']
})
export class ActionsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  userActions: UserAction[];
  modulesArr: MenuModule[];
  
  dataSource?: MatTableDataSource<UserAction>;
  displayedColumns: string[] =  ['ID', 'NOMBRE', 'MODULO', 'SUBMODULO', 'FUNCION', 'PANTALLA', 'TIPACC', 'FECAC', 'ACCIONES'];

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

  public btnSmall: boolean = false;
  public txtBuscador:string;

  constructor(
    private _actionsService: ActionsServiceService,
    private _modulesService: ModulesService,
    private _encService: EncService,
    private _router: Router,
    private _funcService: FunctionsService,
  ) { 
    this.hasError = false;
    this.isLoading = true;
    this.errorStr = "";
    this.userActions = [];
    this.modulesArr = [];
    this.txtBuscador = '';
  }

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

  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 idEnc = localStorage.getItem('idusuario');
      let idDec = await this._encService.desencriptar(idEnc!);
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let menu: MenuResponse = await lastValueFrom(this._modulesService.getMenu(idShort.response.encrypted, 1));

      this.hasError = menu.error;
      if(this.hasError){
        this.errorStr = menu.msg;
        this.isLoading = false;
      }else{
        this.modulesArr = menu.response;
      }

      let actions: ActionsResponse = await lastValueFrom(this._actionsService.getLastActions(idShort.response.encrypted, 1));

      this.hasError = actions.error;
      if(this.hasError){
        this.errorStr = actions.msg;
        this.isLoading = false;
      }else{
        if(actions.response.length == 0){
          this.isLoading = false;
        }else{
          actions.response.forEach(action => {
            let completeName = this._funcService.buildName(action.NOMBRE, action.APEPAT, action.APEMAT);
            let moduleObj = this.modulesArr.filter(item => item.IDMODULO == action.IDMODULO);

            let actionReg: UserAction = {
              ID: action.IDUSUARIO,
              NOMBRE: completeName,
              MODULO: '-',
              SUBMODULO: '-',
              FUNCION: '-',
              PANTALLA: '-',
              TIPACC: action.TIPOACCION,
              FECAC: action.FECHAACCION,
            }

            if(moduleObj.length > 0){
              actionReg.MODULO = moduleObj[0].NOMBREMODULO;

              let submoduleObj = moduleObj[0].SUBMODULES.filter(item => item.IDSUBMODULO == action.IDSUBMODULO);
              if(submoduleObj.length > 0){
                actionReg.SUBMODULO = submoduleObj[0].NOMBRESUBMODULO;

                let functionObj = submoduleObj[0].FUNCIONES.filter(item => item.IDFUNCION == action.IDFUNCION);
                if(functionObj.length > 0){
                  actionReg.FUNCION = functionObj[0].NOMBREFUNCION;

                  let screenObj = functionObj[0].PANTALLAS.filter(item => item.IDPANTALLA == action.IDPANTALLA);
                  if(screenObj.length > 0){
                    actionReg.PANTALLA = screenObj[0].NOMBREPANTALLA;
                  }
                }
              }

              let functionObj = moduleObj[0].MENUS.filter(item => item.IDFUNCION == action.IDFUNCION);
              if(functionObj.length > 0){
                actionReg.FUNCION = functionObj[0].NOMBREFUNCION;

                let screenObj = functionObj[0].PANTALLAS.filter(item => item.IDPANTALLA == action.IDPANTALLA);
                if(screenObj.length > 0){
                  actionReg.PANTALLA = screenObj[0].NOMBREPANTALLA;
                }
              }
            }

            if(action.IDUSUARIO != idDec){
              this.userActions.push(actionReg);
            }
          });
          
          this.dataSource = new MatTableDataSource(this.userActions);
          this.dataSource.paginator = this.paginator!;
          this.dataSource.sort = this.sort!;
          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;
      }
    }
  }

  buildDate(date: string): string{
    if(date == "" || date == null || date == undefined){
      return '-';
    }

    let dateTimeArr = date.split(" ");
    let dateArr = dateTimeArr[0].split("-");
    dateArr = dateArr.reverse();

    let timeArr = dateTimeArr[1].split(":");
    let hour = timeArr[0];
    let timeStr = "";

    if(parseInt(hour) > 12){
      let hourPM = parseInt(hour) - 12 > 10 ? `${hour}` : `0${parseInt(hour) - 12}`;
      timeStr += `${hourPM}:${timeArr[1]} PM`;
    }else{
      timeStr += `${hour}:${timeArr[1]} AM`;
    }
    
    return `${dateArr.join("/")} ${timeStr}`;
  }

  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.encriptar(id);
    this._router.navigate(['sam/ADSI/SAUS/detalles'], {
      queryParams: {
        info: idEnc
      }
    });
  }

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

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