import { Component, Inject, OnInit } from '@angular/core';
import { PreventiveOrderExecution, PreventiveOrderExecutionResponse } from '../../../../interfaces/preventive-order-execution.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-execution-dialog',
    templateUrl: './execution-dialog.component.html',
    styleUrl: './execution-dialog.component.css',
    standalone: false
})
export class ExecutionDialogComponent implements OnInit {
  idOrder: number;
  dateStr: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  prevOrdExec?: PreventiveOrderExecution;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _functionsService: FunctionsService,
    private _dialogRef: MatDialogRef<ExecutionDialogComponent>,
    private _dialog: MatDialog
  ) { 
    this.idOrder = 0;
    this.dateStr = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr  = '';
  }

  ngOnInit(): void {
    this.idOrder = this._data.idOrder;
    
    let orderDateArr = this._data.date.split('-');
    this.dateStr = `${parseInt(orderDateArr[2])} de ${this.MONTHS[parseInt(orderDateArr[1]) - 1]} del ${orderDateArr[0]}`;
    this.getExecReg();
  }

  async getExecReg(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${this._data.idOrder}`);
      let execRegister: PreventiveOrderExecutionResponse = await lastValueFrom(this._prevMaintService.getExecRegister(
        this._data.date, 
        idOrderEnc, 
        idUser, 
        1
      ));
      
      this.hasError = execRegister.error;
      this.errorStr = execRegister.msg;

      if(!this.hasError){
        this.prevOrdExec = execRegister.response;
        let equipmentEncrypted = await this._encService.isEncrypted(this.prevOrdExec.EQUIPAMIENTO);

        if(equipmentEncrypted){
          this.prevOrdExec.EQUIPAMIENTO = await this._encService.decrypt(this.prevOrdExec.EQUIPAMIENTO);
        }
      }

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

  orderDate(date: string): string{
    return this._functionsService.orderDate(date)!;
  }

  closeDialog(action: string){
    if(action == 'cancel' || action == 'end'){
      let obsRef = this._dialog.open(ObservationsDialog, {
        disableClose: true,
        width: '420px',
        maxWidth: '420px',
      });

      obsRef.afterClosed().subscribe(res => {
        if(res != '' && res != undefined && res != null){
          if(action == 'end'){
            this._dialogRef.close(`${action}|${res}|${this.prevOrdExec?.IDREG}`);
          }else{
            this._dialogRef.close(`${action}|${res}`);
          }
        }
      });
    }else{
      this._dialogRef.close(action);
    }
  }
}

@Component({
    selector: 'observations-dialog',
    templateUrl: './observations-dialog.html',
    standalone: false
})
export class ObservationsDialog {}
