import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { EquipmentDetails, EquipmentDetailsResponse } from 'src/app/interfaces/equipment-management.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { EquipmentManagementService } from 'src/app/services/equipment-management.service';

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

  codeTypes = {
    1: "General",
    2: "PCC",
    3: "Origen y destino para líneas y enlaces",
    4: "Origen y destino para estaciones y edificios",
    5: "Tren",
    6: "Origen y destino mixto"
  };

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

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

  async getEquipment(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipment: EquipmentDetailsResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultOnly(
        this._data.code,
        idUser,
        1
      ));

      this.hasError = equipment.error;
      this.errorStr = equipment.msg;
      
      if(!this.hasError){
        this.equipment = equipment.response;
        this.equipment.CODIGO = await this._encService.decrypt(this.equipment.CODIGO);

        let codeType = parseInt(this.equipment.TIPO_CODIGO);
        this.equipment.TIPO_CODIGO = `${this.codeTypes[codeType as never]} (${this.equipment.TIPO_CODIGO})`;
        this.equipment.TIPO_EQUIPAMIENTO = await this._encService.decrypt(this.equipment.TIPO_EQUIPAMIENTO);
        this.equipment.MODELO = await this._encService.decrypt(this.equipment.MODELO);
        console.log(equipment);
      }

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

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