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 { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { EquipmentDetailsDialogComponent } from '../../new-equipment/equipment-details-dialog/equipment-details-dialog.component';
import { ViaLevel } from '../via-level-selector/via-level-selector.component';

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

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

    this.equipments = [];
    this.viaLevels = [
      { code: 'S01', name: 'Nivel sobre túnel' },
      { code: 'S02', name: 'Nivel techo - túnel' },
      { code: 'S03', name: 'Nivel túnel' },
      { code: 'S04', name: 'Nivel vía' },
      { code: 'S05', name: 'Nivel debajo de vía' },
    ];
  }

  ngOnInit(): void {
    let infoObj = JSON.parse(this._data.info);
    let levelFilt = this.viaLevels.filter(item => item.code == infoObj.level);

    this.title = `Tramo del kilómetro ${infoObj.startKM} al kilómetro ${infoObj.endKM}`;
    this.viaLevel = infoObj.level;

    if(levelFilt.length > 0){
      this.title += `, ${levelFilt[0].name} (${levelFilt[0].code})`;
    }

    this.getEquipmentsByKilometer(infoObj.startKM, infoObj.endKM);
  }

  async getEquipmentsByKilometer(startPK: number, endPK: number){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultByKilometer(
        startPK,
        endPK,
        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})`;

          if(equipment.NIVEL_ORIGEN == this.viaLevel || equipment.NIVEL_ORIGEN == this.viaLevel){
            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: '920px',
      maxWidth: '920px',
      data: {
        code: equipmentCode,
      }
    });
  }
}
