import { Component, Inject, OnInit } from '@angular/core';
import { EquipmentsListItem, EquipmentsListResponse } from '../../../../interfaces/equipment-management.interface';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-copy-order',
    templateUrl: './copy-order.component.html',
    styleUrl: './copy-order.component.css',
    standalone: false
})
export class CopyOrderComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  
  idOrder: number;
  equipments: EquipmentsListItem[];

  equipmentControl = new FormControl('', Validators.required);

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<CopyOrderComponent>,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _equipmentManagementService: EquipmentManagementService,
    private _resourcesService: ResourcesService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.idOrder = 0;
    this.equipments = [];
  }

  ngOnInit(): void {
    this.idOrder = parseInt(this._data.idOrder);
    this.getEquipments();
  }

  async getEquipments(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsult(idUser, 1));

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

      if(!this.hasError){
        let equipmentsArr: EquipmentsListItem[] = [];
        for(const equipment of equipments.response){
          let equipmentCodeDec = await this._encService.decrypt(equipment.CODIGO);
          equipment.TIPO = `${equipmentCodeDec} - ${equipment.TIPO}`;

          let idEquipmentDec = await this._encService.decrypt(equipment.ID_EQUIPO);
          equipment.MODELO = `${equipment.MODELO} (${idEquipmentDec})`;

          if(this._data.equipment != equipmentCodeDec){
            equipmentsArr.push(equipment);
          }
        }
        
        this.equipments = equipmentsArr;
      }

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

  async copyOrder(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idOrderEnc = await this._encService.encrypt(`${this.idOrder}`);
      let formData = new FormData();
      
      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_order', idOrderEnc);
      formData.append('equipment', this.equipmentControl.value!);
      
      await lastValueFrom(this._prevMaintService.copyWorkOrder(formData));
      
      this._resourcesService.openSnackBar('La orden fue copiada correctamente.');
      this._dialogRef.close();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
