import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { PendingEquipmentDetails, PendingEquipmentResponse } 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-pre-code-details',
  templateUrl: './pre-code-details.component.html',
  styleUrls: ['./pre-code-details.component.css']
})
export class PreCodeDetailsComponent implements OnInit {
  code: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  preCodeDetails: PendingEquipmentDetails | 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 _equimpentManagementService: EquipmentManagementService,
    private _encService: EncService,
  ) {
    this.code = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.preCodeDetails = null;
  }

  ngOnInit(): void {
    this.code = this._data.preCode;
    this.getData();
  }

  async getData(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let preCodeData: PendingEquipmentResponse = await lastValueFrom(this._equimpentManagementService.equipmentConsultPendingOnly(
        this._data.idReg,
        idUser,
        1
      ));

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

      if(!this.hasError){
        this.preCodeDetails = preCodeData.response;
        this.preCodeDetails.TIPO_EQUIPAMIENTO = await this._encService.decrypt(this.preCodeDetails.TIPO_EQUIPAMIENTO);
        this.preCodeDetails.MODELO_EQUIPAMIENTO = await this._encService.decrypt(this.preCodeDetails.MODELO_EQUIPAMIENTO);
        this.preCodeDetails.PROVEEDOR = await this._encService.decrypt(this.preCodeDetails.PROVEEDOR as string);

        let codeType = parseInt(this.preCodeDetails.TIPO_CODIGO);
        this.preCodeDetails.TIPO_CODIGO = `${this.codeTypes[codeType as never]} (${this.preCodeDetails.TIPO_CODIGO})`;
      }

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