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

export interface NoMeasuresOrderDetailsField{
  label: string;
  value: string;
}
@Component({
    selector: 'app-no-measures-order-details',
    templateUrl: './no-measures-order-details.component.html',
    styleUrl: './no-measures-order-details.component.css',
    standalone: false
})
export class NoMeasuresOrderDetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idOrder: string;
  order: NoMeasuresOrder | null;
  displayedData: NoMeasuresOrderDetailsField[];

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

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

  private async getNoMeasuresOrderDetails(){
    try{
      this.idOrder = await this._encService.decrypt(this._data.idOrder);

      let idUser = localStorage.getItem('idusuario')!;
      let noMeasuresOrderDetails: NoMeasuresOrderResponse = await lastValueFrom(this._correctiveMaintenanceService.getNoMeasuresOrder(
        this._data.idOrder,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let formFields: CorrectiveMaintenanceOrderField[] = [];
        for(const field of noMeasuresOrderDetails.response.FORMULARIO.CAMPOS){
          field.fieldID = await this._encService.decrypt(field.fieldID);
          formFields.push(field);
        }

        let dataDec = await this._encService.decrypt(noMeasuresOrderDetails.response.DATOS.DATOS);
        let dataObj = JSON.parse(dataDec);
        let dataKeys = Object.keys(dataObj);

        let formValues: NoMeasuresOrderDetailsField[] = [];
        for(const key of dataKeys){
          let fieldFilt = formFields.filter(item => item.fieldID == key);
          if(fieldFilt.length > 0){
            let fieldVal = dataObj[key];
            if(fieldFilt[0].fieldType == 'SE-4'){
              let selectedOptionDec = await this._encService.decrypt(fieldVal);
              let selectedOptionFilt = fieldFilt[0].selectorOptions.filter(option => option.value == fieldVal);
              if(selectedOptionFilt.length > 0){
                fieldVal = `${selectedOptionFilt[0].label} (${selectedOptionDec})`;
              }else{
                fieldVal = selectedOptionDec;
              }
            }else if(fieldFilt[0].fieldType == 'FE-2'){
              fieldVal = this._functionsService.buildHumanDate(fieldVal);
            }else if(fieldFilt[0].validators.includes('HORA')){
              fieldVal = this._functionsService.convertFullHourToHumanHour(fieldVal);
            }
            
            let formField: NoMeasuresOrderDetailsField = {
              label: fieldFilt[0].label,
              value: fieldVal,
            };

            formValues.push(formField);
          }
        }

        this.displayedData = formValues;
      }

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