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

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

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

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

  private async getCorrectiveWorkOrder(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let order: WorkOrderStatusHistoryListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderStatusHistory(
        this._data.idOrder, 
        idUser, 
        1
      ));

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

      if(!this.hasError){
        let validatedStatusFilt = order.response.filter(item => item.ESTADO == 'Validado');
        if(validatedStatusFilt.length > 0){
          let idUserActionDec = await this._encService.decrypt(this._data.idUserAction);
          let userStaffValidation = validatedStatusFilt[0].PERSONAL!.filter(item => item == idUserActionDec);

          if(userStaffValidation.length > 0){
            let userAttendanceValidation = validatedStatusFilt[0].ATENCION!.filter(item => item.ID == idUserActionDec);
            if(userAttendanceValidation.length > 0){
              this.comments = userAttendanceValidation[0].COMENTARIOS!;
            }else{
              this.hasError = true;
              this.errorStr = 'El usuario asociado aún no ha respondido a la orden de mantenimiento consultada.';
            }
          }else{
            this.hasError = true;
            this.errorStr = 'El usuario asociado no está asignado a la orden de mantenimiento consultada.';
          }
        }else{
          this.hasError = true;
          this.errorStr = 'La orden consultada no ha sido validada.';
        }
      }

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