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

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

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

  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){
        this.isLoading = false;
      }else{
        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.getSignatureFile(userAttendanceValidation[0].FIRMA!);
            }else{
              this.isLoading = false;
              this.hasError = true;
              this.errorStr = 'El usuario asociado aún no ha respondido a la orden de mantenimiento consultada.';
            }
          }else{
            this.isLoading = false;
            this.hasError = true;
            this.errorStr = 'El usuario asociado no está asignado a la orden de mantenimiento consultada.';
          }
        }else{
          this.isLoading = false;
          this.hasError = true;
          this.errorStr = 'La orden consultada no ha sido validada.';
        }
      }
    }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;
    }
  }

  private async getSignatureFile(signatureCode: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let signatureCodeEnc = await this._encService.encrypt(signatureCode);
      let signatureFile = await lastValueFrom(this._gdelService.getPublicDocumentUrl(
        signatureCodeEnc, 
        idUser, 
        1
      ));

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

      if(!this.hasError){
        this.signatureFileURI = signatureFile.response.public_uri;
      }

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