import { Component, Inject, OnInit } from '@angular/core';
import { TrainOccupationsListItem } from '../../../../interfaces/equipment-management.interface';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';

@Component({
    selector: 'app-locate-car',
    templateUrl: './locate-car.component.html',
    styleUrl: './locate-car.component.css',
    standalone: false
})
export class LocateCarComponent implements OnInit {
  trainOccupations: TrainOccupationsListItem[];
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  selectedCar: string;
  image: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<LocateCarComponent>,
  ) {
    this.trainOccupations = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.selectedCar = "";
    this.image = "";
  }

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

  async init(){
    let trainOccupations: TrainOccupationsListItem[] = [];
    for(const occupation of this._data.trainOccupations){
      let codeDec = await this._encService.decrypt(occupation.CODE);
      occupation.IMAGE = `${codeDec}.png`;

      trainOccupations.push(occupation);
    }

    this.trainOccupations = trainOccupations;
    this.isLoading = false;
  }

  async selectCar(car: TrainOccupationsListItem){
    this.selectedCar = car.CAR;
    this.image = car.IMAGE!;
  }

  close(){
    this._dialogRef.close(this.selectedCar);
  }
}
