import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { ActivatedRoute } from '@angular/router';
import { FailureAnalysisService } from '../../../../services/failure-analysis/failure-analysis.service';
import { lastValueFrom } from 'rxjs';
import { ResponseDataDetailsHistory } from '../../../../interfaces/failure-analysis/failure.interface';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-details-history-failure-equipment',
    templateUrl: './details-history-failure-equipment.component.html',
    styleUrl: './details-history-failure-equipment.component.css',
    standalone: false
})
export class DetailsHistoryFailureEquipmentComponent implements OnInit {
  public isLoading: boolean;
  public titleDialog: string;
  public formGroup: FormGroup;
  public failureNumber: string;
  public equipmentCode: string;

  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _activatedRoute: ActivatedRoute,
    private _failureAnalysisService: FailureAnalysisService,
  ) {
    this.isLoading = false;
    this.titleDialog = ``;
    this.failureNumber = ``;
    this.equipmentCode = ``;
    this.formGroup = this.createFormGroup();
  }

  private createFormGroup() {
    return new FormGroup({
      NUMERO_FALLA: new FormControl(''),
      CODIGO_EQUIPAMIENTO: new FormControl(''),
      ESTADO_FALLA: new FormControl(''),
      NOMBRE_FALLA: new FormControl(''),
      CAUSA_FALLA: new FormControl(''),
      NIVEL_CRITICIDAD_FALLA: new FormControl(''),
      NOMBRE_SINTOMA: new FormControl(''),
      CAUSA_SINTOMA: new FormControl(''),
      CLASIFICACION_SINTOMA: new FormControl(''),
      FECHA_FALLA: new FormControl(''),
      FECHA_RESOLUCION: new FormControl(''),
      REPARABLE: new FormControl(''),
      VALOR_OBTENIDO: new FormControl(''),
      NOMBRE_MEDIDA: new FormControl(''),
      SOLUCION: new FormControl(''),
      COMENTARIOS: new FormControl(''),
    });
  }

  async ngOnInit() {
    this.isLoading = true;

    const encFailure = this._activatedRoute.snapshot.paramMap.get(`failure`);
    if (encFailure === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al recuperar el número de falla.`);
      this.resourcesService.goBack();
      return;
    }
    const encEquipment = this._activatedRoute.snapshot.paramMap.get(`equipment`);
    if (encEquipment === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al recuperar el equipamiento.`);
      this.resourcesService.goBack();
      return;
    }

    this.failureNumber = await this._encService.decrypt(encFailure);
    this.equipmentCode = await this._encService.decrypt(encEquipment);

    await this.getDetailsHistoryFailureEquipment();

    this.isLoading = false;
  }

  public async getDetailsHistoryFailureEquipment() {
    const encFailure: string = await this._encService.encrypt(this.failureNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.getDetailsHistoryFailureEquipment(encFailure, user, line)).then(
      (responseData: ResponseDataDetailsHistory) => {
        if (!responseData.error) {
          
          let numero_falla = responseData.response.NUMERO_FALLA;
          let codigo_equipamiento = responseData.response.CODIGO_EQUIPAMIENTO;
          let estado_falla = responseData.response.ESTADO_FALLA;
          let nombre_falla = responseData.response.NOMBRE_FALLA;
          let causa_falla = responseData.response.CAUSA_FALLA;
          let nivel_criticidad_falla = responseData.response.NIVEL_CRITICIDAD_FALLA;
          let nombre_sintoma = responseData.response.NOMBRE_SINTOMA;
          let causa_sintoma = responseData.response.CAUSA_SINTOMA;
          let clasificacion_sintoma = responseData.response.CLASIFICACION_SINTOMA;
          let fecha_falla = this.resourcesService.formatOnlyDatetime(responseData.response.FECHA_FALLA);
          let fecha_resolucion = null          
          if (responseData.response.FECHA_RESOLUCION !== null)  {
            fecha_resolucion = this.resourcesService.formatOnlyDatetime(responseData.response.FECHA_RESOLUCION);
          }
          let reparable = responseData.response.REPARABLE === 1 ? 'Si' : 'No';
          let valor_obtenido = `${responseData.response.VALOR_OBTENIDO} ${responseData.response.ACRONIMO_MEDIDA}`;
          let nombre_medida = responseData.response.NOMBRE_MEDIDA
          let solucion = responseData.response.SOLUCION;
          let comentarios = responseData.response.COMENTARIOS;

          this.formGroup.controls['NUMERO_FALLA'].setValue( numero_falla );
          this.formGroup.controls['CODIGO_EQUIPAMIENTO'].setValue( codigo_equipamiento );
          this.formGroup.controls['ESTADO_FALLA'].setValue( estado_falla );
          this.formGroup.controls['NOMBRE_FALLA'].setValue( nombre_falla );
          this.formGroup.controls['CAUSA_FALLA'].setValue( causa_falla );
          this.formGroup.controls['NIVEL_CRITICIDAD_FALLA'].setValue( nivel_criticidad_falla );
          this.formGroup.controls['NOMBRE_SINTOMA'].setValue( nombre_sintoma );
          this.formGroup.controls['CAUSA_SINTOMA'].setValue( causa_sintoma );
          this.formGroup.controls['CLASIFICACION_SINTOMA'].setValue( clasificacion_sintoma );
          this.formGroup.controls['FECHA_FALLA'].setValue( fecha_falla );
          this.formGroup.controls['FECHA_RESOLUCION'].setValue( fecha_resolucion );
          this.formGroup.controls['REPARABLE'].setValue( reparable );
          this.formGroup.controls['VALOR_OBTENIDO'].setValue( valor_obtenido );
          this.formGroup.controls['NOMBRE_MEDIDA'].setValue( nombre_medida );
          this.formGroup.controls['SOLUCION'].setValue( solucion );
          this.formGroup.controls['COMENTARIOS'].setValue( comentarios );

        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDetailsHistoryFailureEquipment();
        }
      }
    );
  }
}
