import { Component, Inject, OnInit } from '@angular/core';
import { PendingEquipmentsListItem, PendingEquipmentsListResponse } from '../../../interfaces/equipment-management.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-group-pending',
    templateUrl: './group-pending.component.html',
    styleUrl: './group-pending.component.css',
    standalone: false
})
export class GroupPendingComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  action: string;
  selectedGroup: string;

  pendingGroups: PendingEquipmentsListItem[];
  images: Map<string, string[]>;
  imagesIndexes: Map<string, number>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _equipmentManagementService: EquipmentManagementService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<GroupPendingComponent>,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.action = '';
    this.selectedGroup = '';

    this.pendingGroups = [];
    this.images = new Map();
    this.imagesIndexes = new Map();
  }

  ngOnInit(): void {
    this.action = this._data.action == 'aprove' ? 'Aprobar' : 'Rechazar';
    this.getGroupedPendingEquipments();
  }

  async getGroupedPendingEquipments(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let pendingGrouped: PendingEquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultPendingGrouped(idUser, 1));

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

      if(!this.hasError){
        let pendingGroupedArr: PendingEquipmentsListItem[] = [];
        for(const group of pendingGrouped.response){
          group.CODIGO = await this._encService.decrypt(group.CODIGO);
          group.TIPO_EQUIPAMIENTO = await this._encService.decrypt(group.TIPO_EQUIPAMIENTO);
          group.MODELO_EQUIPAMIENTO = await this._encService.decrypt(group.MODELO_EQUIPAMIENTO);

          let galleryArr = JSON.parse(group.GALERIA_IMAGENES as string);
          let gallery: string[] = [];
          for(const imageStr of galleryArr){
            let imageDec = await this._encService.decrypt(imageStr);
            gallery.push(imageDec);
          }

          group.GALERIA_IMAGENES = gallery;
          pendingGroupedArr.push(group);
          
          this.images.set(group.CODIGO, group.GALERIA_IMAGENES);
          this.imagesIndexes.set(group.CODIGO, 0);
        }
        
        this.pendingGroups = pendingGroupedArr;
      }

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

  backward(code: string){
    let index = this.imagesIndexes.get(code)! - 1;
    if(index < 0){
      this.imagesIndexes.set(code, this.images.get(code)!.length - 1);
    }else{
      this.imagesIndexes.set(code, index);
    }
  }

  forward(code: string){
    let index = this.imagesIndexes.get(code)! + 1;
    if(index > this.images.get(code)!.length - 1){
      this.imagesIndexes.set(code, 0);
    }else{
      this.imagesIndexes.set(code, index);
    }
  }

  alertProcessPendingEquipments(){
    let groupFilt = this.pendingGroups.filter(item => item.CODIGO == this.selectedGroup);
    if(groupFilt.length > 0){
      let actionLower = this.action.toLowerCase();
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: 'Confirmación',
          icon: 'warning',
          description: `¿Está seguro de ${actionLower} ${groupFilt[0].TOTAL} elementos?`,
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.processPendingElements();
        }
      });
    }
  }

  private async processPendingElements(){
    let codeEnc = await this._encService.encrypt(this.selectedGroup);
    this._dialogRef.close(codeEnc);
  }
}
