import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { LocationsListItem, LocationsListResponse } from '../../../interfaces/equipment-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-locations-management',
    templateUrl: './locations-management.component.html',
    styleUrl: './locations-management.component.css',
    standalone: false
})
export class LocationsManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  dataSource: MatTableDataSource<LocationsListItem>;
  displayedColumns = ['LOCATION', 'CODE'];

  public txtBuscador: string;

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

  constructor(
    private _equipmentManagementService: EquipmentManagementService,
    private _encService: EncService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.dataSource = new MatTableDataSource();
    this.txtBuscador = '';
  }

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

  async getLocations(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let locations: LocationsListResponse = await lastValueFrom(this._equipmentManagementService.locationConsult(idUser, 1));

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

      if(!this.hasError){
        let locationsArr: LocationsListItem[] = [];
        for(const location of locations.response){
          let locationDec = await this._encService.decrypt(location.LOCATION);
          let codeDec = await this._encService.decrypt(location.CODE);

          location.LOCATION = locationDec;
          location.CODE = codeDec;

          locationsArr.push(location);
        }

        this.dataSource = new MatTableDataSource(locationsArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    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();
    }
  }
}
