import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { InterventionsListItem } from 'src/app/interfaces/personal-managment/intervention.interface';
import { OrderExecutionDetails, OrderExecutionDetailsResponse } from 'src/app/interfaces/preventive-order-execution.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { FunctionsService } from 'src/app/services/functions.service';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';

@Component({
  selector: 'app-intervention-details',
  templateUrl: './intervention-details.component.html',
  styleUrls: ['./intervention-details.component.css']
})
export class InterventionDetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  intervention: InterventionsListItem;
  title: string;
  orderExecution: OrderExecutionDetails | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: InterventionsListItem,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _prevMaintService: PreventiveMaintenanceService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.intervention = this._data;
    this.title = "";
    this.orderExecution = null;
  }

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

  async init(){
    let idRegDec = await this._encService.decrypt(this.intervention.IDREG);
    let idRegArr = idRegDec.split('|');
    let formattedDate = this._functionsService.buildHumanDate(idRegArr[1]);
    let idWorkOrder = await this._encService.decrypt(`${this.intervention.IDORDER}`);
    let idRegStr = `${idRegArr[0]}|1|${idWorkOrder}|${idRegArr[1]}`;

    this.title = `Ejecución del ${formattedDate}`;
    this.getExecutionDetails(idRegStr);
  }

  async getExecutionDetails(idReg: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idRegEnc = await this._encService.encrypt(idReg);
      let execution: OrderExecutionDetailsResponse = await lastValueFrom(this._prevMaintService.getOrderExecutionDetails(idRegEnc, idUser, 1));

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

      if(!this.hasError){
        this.orderExecution = execution.response;
        this.orderExecution.IDREGISTRO = await this._encService.decrypt(`${this.orderExecution.IDREGISTRO}`);
        this.orderExecution.IDORDEN = await this._encService.decrypt(`${this.orderExecution.IDORDEN}`);
        this.orderExecution.FECHAEJECUCION = this._functionsService.orderDate(this.orderExecution.FECHAEJECUCION);
        this.orderExecution.FECHAPROGRAMACION = this._functionsService.buildHumanDate(this.orderExecution.FECHAPROGRAMACION);

        if(this.orderExecution.FECHAFINALIZACION != null){
          this.orderExecution.FECHAFINALIZACION = this._functionsService.orderDate(this.orderExecution.FECHAFINALIZACION);
        }
      }

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