import { MapViewerComponent } from './map-viewer/map-viewer.component';
import { MatDialog } from '@angular/material/dialog';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { SingleConnection, UserConnectionsInterface, LoginPlace } from './../../../../interfaces/user-connections.interface';
import { ConnectionsService } from './../../../../services/connections.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';

@Component({
  selector: 'app-user-connections',
  templateUrl: './user-connections.component.html',
  styleUrls: ['./user-connections.component.css']
})
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'];

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

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

  constructor(
    private _activeRoute: ActivatedRoute,
    private _encService: EncService,
    private _snackBar: MatSnackBar,
    private _location: Location,
    private _connectionsService: ConnectionsService,
    private _dialog: MatDialog
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.userName = "";
    this.userID = "";
    this.hasConnections = false;
    this.txtBuscador = '';
  }

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

  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.openSnackBar('No se encontró información');
        this._location.back();
      }else{
        this.getData(idEnc);
      }
    });
  }

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

  async getData(id: string){
    try{
      let idDec = await this._encService.desencriptar(id);
      this.userID = idDec;
      let idShort = await lastValueFrom(this._encService.shortEncrypt(id));

      let idEnc = localStorage.getItem('idusuario');
      let idUserShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let connections: UserConnectionsInterface = await lastValueFrom(this._connectionsService.getUserConnections(
        idShort.response.encrypted,
        idUserShort.response.encrypted,
        1
      ));
      this.isLoading = false;
      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!;
      }
    }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();
  }

  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,
      }
    })
  }

  back(){
    this._location.back();
  }

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

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