import { Component, OnInit } from '@angular/core';
import { EquipmentsListItem, EquipmentsListResponse, EquipmentTypesListItem, EquipmentTypesListResponse } from '../../../interfaces/equipment-management.interface';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { ResourcesService } from '../../../services/resources.service';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EquipmentDetailsDialogComponent } from '../new-equipment/equipment-details-dialog/equipment-details-dialog.component';

@Component({
    selector: 'app-equipment-types-management',
    templateUrl: './equipment-types-management.component.html',
    styleUrl: './equipment-types-management.component.css',
    standalone: false
})
export class EquipmentTypesManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  searchingEquipments: boolean;

  equipmentTypesArr: EquipmentTypesListItem[];
  equipmentsByType: EquipmentsListItem[];

  constructor(
    private _equipmentManagementService: EquipmentManagementService,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.searchingEquipments = false;

    this.equipmentTypesArr = [];
    this.equipmentsByType = [];
  }

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

  async getEquipmentTypes(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipmentTypes: EquipmentTypesListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultTypes(idUser, 1));

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

      if(!this.hasError){
        this.equipmentTypesArr = equipmentTypes.response
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  onResize():void{
    
  }

  async searchEquipments(index: number){
    try{
      this.searchingEquipments = true;
      this.equipmentsByType = [];

      let equipmentType = this.equipmentTypesArr[index];
      let equipmentTypeStr = encodeURI(equipmentType.TIPO_EQUIPAMIENTO);
      let idUser = localStorage.getItem('idusuario')!;

      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultByType(
        equipmentTypeStr,
        idUser,
        1
      ));

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

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

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

          equipmentsArr.push(equipment);
        }

        this.equipmentsByType = equipmentsArr;
      }

      this.searchingEquipments = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (3).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (4).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingEquipments = false;
    }
  }

  openEquipmentForm(equipmentType: string){
    let validEquipmentType = encodeURI(equipmentType);
    this._router.navigate(['sam/GEEQ/REEQ'], {
      queryParams: {
        equipmentType: validEquipmentType,
        action: 'new'
      }
    });
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  openEquipmentDetails(codeEnc: string){
    this._dialog.open(EquipmentDetailsDialogComponent, {
      width: '840px',
      maxWidth: '840px',
      data: {
        code: codeEnc,
      }
    });
  }
}
