import { ScriptDialogComponent } from './script-dialog/script-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { UserActionsResponse, Action } from './../../../../interfaces/user-actions.interface';
import { ActionsServiceService } from './../../../../services/actions-service.service';
import { lastValueFrom } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { EncService } from './../../../../services/enc/enc.service';
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string
  userName: string;

  actions: Action[];

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

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

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

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _location: Location,
    private _snackBar: MatSnackBar,
    private _actionsService: ActionsServiceService,
    private _dialog: MatDialog
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.userName = "";

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

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

  refresh(){
    this._activatedRoute.queryParams.subscribe(params =>{
      let info = params['info'];
      if(info == undefined || info == null || info == ""){
        this.openSnackBar('No se encontró información suficiente');
        this._location.back();
      }else{
        this.getData(info);
      }
    });
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, 'Cerrar', {
      duration: 5000
    })
  }

  async getData(id: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idUserShort = await lastValueFrom(this._encService.shortEncrypt(idUser!));

      let idShort = await lastValueFrom(this._encService.shortEncrypt(id));
      
      let userActions: UserActionsResponse = await lastValueFrom(this._actionsService.getUserActions(
        idShort.response.encrypted, 
        idUserShort.response.encrypted, 
        1
      ));
      
      this.isLoading = false;
      this.hasError = userActions.error;
      this.errorStr = userActions.msg;

      if(!this.hasError){
        this.userName = this.buildName(userActions.response.NOMBRE, userActions.response.APEPAT, userActions.response.APEMAT);
        userActions.response.HISTORIAL.forEach(item => {
          let action: Action = {
            MODULO: item.MODULO == null ? '-' : item.MODULO,
            SUBMODULO: item.SUBMODULO == null ? '-' : item.SUBMODULO,
            FUNCION: item.FUNCION == null ? '-' : item.FUNCION,
            PANTALLA: item.PANTALLA == null ? '-' : item.PANTALLA,
            TIPOACCION: item.TIPOACCION,
            DESCRIPCION: item.DESCRIPCION,
            FECHA: item.FECHA,
          }

          this.actions.push(action);
        });
        
        this.dataSource = new MatTableDataSource(this.actions);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }
    }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;
      }
    }
  }

  buildName(no: string, ap: string, am: string): string{
    let name = `${no} ${ap}`;
    if(am != undefined && am != null && am != ""){
      name += ` ${am}`;
    }

    return name;
  }

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

  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}`;
  }

  openDialog(script: string, params: string){
    this._dialog.open(ScriptDialogComponent, {
      data: {
        script: script,
        params: params
      }
    })
  }

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

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

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