import { Component, Inject, OnInit } from '@angular/core';
import { WorkGroupDetails, WorkGroupDetailsResponse, WorkGroupRelatedTeam } from '../../../../interfaces/corrective-maintenance.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-work-group-details',
    templateUrl: './work-group-details.component.html',
    styleUrl: './work-group-details.component.css',
    standalone: false
})
export class WorkGroupDetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  workGroup: WorkGroupDetails | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.workGroup = null;
  }

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

  async getWorkGroup(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let workGroup: WorkGroupDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkGroup(
        this._data.idGroup,
        idUser,
        1
      ));

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

      if(!this.hasError){
        workGroup.response.ID_GRUPO = await this._encService.decrypt(workGroup.response.ID_GRUPO);
        
        let relatedTeamsArr: WorkGroupRelatedTeam[] = JSON.parse(workGroup.response.EQUIPOS_RELACIONADOS);
        let relatedTeamsArrFn: WorkGroupRelatedTeam[] = [];
        for(const team of relatedTeamsArr){
          let idTeamDec = await this._encService.decrypt(team.ID_EQUIPO);
          team.NOMBRE_EQUIPO = `${team.NOMBRE_EQUIPO} (${idTeamDec})`;

          relatedTeamsArrFn.push(team);
        }

        workGroup.response.EQUIPOS_RELACIONADOS_ARR = relatedTeamsArrFn;
        workGroup.response.FECREG = this._functionsService.orderDate(workGroup.response.FECREG);

        if(workGroup.response.FECMOD != null){
          workGroup.response.FECMOD = this._functionsService.orderDate(workGroup.response.FECMOD);
        }
        
        this.workGroup = workGroup.response;
      }

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