import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { SingleConnection, UserConnectionsInterface } from '../../../../interfaces/user-connections.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ConnectionsService } from '../../../../services/connections.service';
import { MatDialog } from '@angular/material/dialog';
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 { Location } from '@angular/common';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { MapViewerComponent } from './map-viewer/map-viewer.component';

@Component({
    selector: 'app-user-connections',
    templateUrl: './user-connections.component.html',
    styleUrl: './user-connections.component.css',
    standalone: false
})
export class UserConnectionsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  userName: string;
  userID: string;
  hasConnections: boolean;

  dataSource!: MatTableDataSource<SingleConnection>;
  displayedColumns: string[] =  ['ID', 'IP', 'FECHA', 'ACCIONES'];

  actionsEnabled: boolean;

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

  // ---- SmartPage ----
  btnSmall: boolean = false;
  txtBuscador:string;

  constructor(
    private _activeRoute: ActivatedRoute,
    private _encService: EncService,
    private _snackBar: MatSnackBar,
    private _location: Location,
    private _connectionsService: ConnectionsService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.userName = "";
    this.userID = "";
    this.hasConnections = false;
    this.txtBuscador = '';
    this.actionsEnabled = true;
  }

  ngOnInit(): void {
    this.refresh();
    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 == 'S002V01F01MAUS');
              if(funPerm.length > 0){
                let actionsEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03DEUB');
                if(actionsEnabled.length > 0){
                  this.actionsEnabled = actionsEnabled[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}`);
        }
      }
    });
  }

  refresh(){
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    
    this._activeRoute.queryParams.subscribe(res => {
      let idEnc = res['info'];
      if(idEnc == undefined || idEnc == null || idEnc == ""){
        this._resourcesService.openSnackBar('No se encontró información');
        this._location.back();
      }else{
        this.getData(idEnc);
      }
    });
  }

  async getData(id: string){
    try{
      let idDec = await this._encService.decrypt(id);
      this.userID = idDec;

      let idEnc = localStorage.getItem('idusuario')!;

      let connections: UserConnectionsInterface = await lastValueFrom(this._connectionsService.getUserConnections(
        id,
        idEnc,
        1
      ));

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

      if(!this.hasError){
        this.userName = this.buildName(
          connections.response.NOMBRE,
          connections.response.APPAT,
          connections.response.APMAT
        );
        
        this.hasConnections = connections.response.HISTORIAL.length > 0;
        this.dataSource = new MatTableDataSource(connections.response.HISTORIAL);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;

        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 == 'S002V01F01MAUS')[0];

        this.actionsEnabled = funPerm.children.filter(item => item.id == 'S002V01P03DEUB')[0].access > 0;
      }

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

  buildName(na: string, fl: string, sl: string): string{
    let name = `${na} ${fl}`;
    if(sl != null && sl != "" && sl != undefined){
      name += ` ${sl}`;
    }
    return name.trim();
  }

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

  buildConnection(date: string){
    let meses = new Map<string, string>([
      ["01", "enero"],
      ["02", "febrero"],
      ["03", "marzo"],
      ["04", "abril"],
      ["05", "mayo"],
      ["06", "junio"],
      ["07", "julio"],
      ["08", "agosto"],
      ["09", "septiembre"],
      ["10", "octubre"],
      ["11", "noviembre"],
      ["12", "diciembre"],
    ]);

    let dateTimeArr = date.split(" ");
    let dateArr = dateTimeArr[0].split("-");
    let timeArr = dateTimeArr[1].split(":");

    let tiempo = parseInt(timeArr[0]) > 12 ? "PM": "AM";
    let hora = parseInt(timeArr[0]) > 12 ? parseInt(timeArr[0]) - 12 : parseInt(timeArr[0]);
    let horaStr = hora < 10 ? `0${hora}` : hora;

    let la = hora == 1 ? "la" : "las";

    return `El ${dateArr[2]} de ${meses.get(dateArr[1])} del ${dateArr[0]} a ${la} ${horaStr}:${timeArr[1]} ${tiempo}`
  }

  seeLocation(lati: number, long: number, prec: number, esta: string, pais: string, ciud?: string){
    let location: string = JSON.stringify({
      lati: lati,
      long: long,
      prec: prec,
      esta: esta,
      pais: pais,
      ciud: ciud
    });
    
    this._dialog.open(MapViewerComponent, {
      data: {
        location: location,
        isLocation: true
      }
    });
  }

  seeDevice(device: string, os: string, vos: string, navigator: string){
    let deviceInfo: string = JSON.stringify({
      device: device,
      os: os,
      vos: vos,
      navigator: navigator
    });

    this._dialog.open(MapViewerComponent, {
      data: {
        deviceInfo: deviceInfo,
        isLocation: false,
      }
    })
  }
}
