import { Component, Inject, OnInit } from '@angular/core';
import { EquipmentsListItem, EquipmentsListResponse } from '../../../../interfaces/equipment-management.interface';
import { MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { lastValueFrom } from 'rxjs';
import { EquipmentDetailsDialogComponent } from '../../new-equipment/equipment-details-dialog/equipment-details-dialog.component';

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

  equipments: EquipmentsListItem[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _equipmentManagementService: EquipmentManagementService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.title = '';

    this.equipments = [];
  }

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

  async init(){
    let elementDec = await this._encService.decrypt(this._data.element);
    let elementObj = JSON.parse(elementDec);

    this.title = `Intersección ${elementObj.coordX}${elementObj.coordY}`;
    this.getPCCElements(`${elementObj.coordX}${elementObj.coordY}`);
  }

  async getPCCElements(intersection: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let intersectionEnc = await this._encService.encrypt(intersection);
      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultByPCCPosition(
        intersectionEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let equipmentsArr: EquipmentsListItem[] = [];
        for(const equipment of equipments.response){
          let equipmentCodeDec = await this._encService.decrypt(equipment.CODIGO);
          equipment.TIPO = `${equipmentCodeDec} - ${equipment.TIPO}`;

          let equipmentIDDec = await this._encService.decrypt(equipment.ID_EQUIPO);
          equipment.MODELO = `${equipment.MODELO} (${equipmentIDDec})`;

          equipmentsArr.push(equipment);
        }
        
        this.equipments = equipmentsArr;
      }
      
      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;
    }
  }

  openEquipmentDetails(equipmentCode: string){
    this._dialog.open(EquipmentDetailsDialogComponent, {
      width: '960px',
      maxWidth: '960px',
      data: {
        code: equipmentCode,
      }
    });
  }
}
