import { Component, Inject, OnInit } from '@angular/core';
import { UnprogrammedVisitDetails, UnprogrammedVisitResponse } from '../../../../interfaces/unprogrammed-visit.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-visit-details',
    templateUrl: './visit-details.component.html',
    styleUrl: './visit-details.component.css',
    standalone: false
})
export class VisitDetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idVisit: number;
  vistDetails: UnprogrammedVisitDetails | null;
  statusMap: Map<string, string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _functionsService: FunctionsService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idVisit = 0;
    this.vistDetails = null;
    this.statusMap = new Map();
  }

  ngOnInit(): void {
    this.statusMap.set('P', 'Pendiente de autorización');
    this.statusMap.set('A', 'Autorizado');
    this.statusMap.set('F', 'Finalizado');
    this.statusMap.set('R', 'Rechazado');
    this.statusMap.set('C', 'Cancelado');

    this.idVisit = this._data.idVisit;
    this.getVisitInfo();
  }

  async getVisitInfo(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idVisitEnc = await this._encService.encrypt(`${this.idVisit}`);
      let visit: UnprogrammedVisitResponse = await lastValueFrom(this._prevMaintService.getUnprogrammedVisit(
        idVisitEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let equipmentCodeDec = await this._encService.decrypt(visit.response.EQUIPAMIENTO);
        visit.response.TIPO_EQUIPAMIENTO = `${equipmentCodeDec} - ${visit.response.TIPO_EQUIPAMIENTO}`;

        let idEquipmentDec = await this._encService.decrypt(visit.response.ID_EQUIPAMIENTO);
        visit.response.MODELO_EQUIPAMIENTO = `${visit.response.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;

        let staffArr = JSON.parse(visit.response.PERSONAL);
        for(const item of staffArr){
          item.ID = await this._encService.decrypt(item.ID);

          if(item.TYPE == 'EQ'){
            item.TYPE = 'Equipo de trabajo';
          }else if(item.TYPE == 'SU'){
            item.TYPE = 'Subcontratista';
          }else if(item.TYPE == 'EM'){
            item.TYPE = 'Empleado';
          }
        }

        visit.response.PERSONAL_ARR = staffArr;
        console.log(visit.response);
        this.vistDetails = visit.response;
      }

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

      this.hasError = true;
      this.isLoading = false;
    }
  }
  
  getComments(commentsStr: string, index: string): string{
    let commentsArr = JSON.parse(commentsStr);
    if(commentsArr[index] != undefined){
      return commentsArr[index];
    }
    return "";
  }

  orderDate(dateStr: string): string{
    return this._functionsService.orderDate(dateStr)!;
  }
}
