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

@Component({
    selector: 'app-pre-code-details',
    templateUrl: './pre-code-details.component.html',
    styleUrl: './pre-code-details.component.css',
    standalone: false
})
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);
        if(codeType == 7){
          this.preCodeDetails.TIPO_CODIGO = `Stock (${this.preCodeDetails.TIPO_CODIGO})`;
        }else{
          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 (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;
    }
  }
}
