import { Component, Inject, OnInit } from '@angular/core';
import { CounterDetails, CounterDetailsResponse, CountersListItem, CountersListResponse } from '../../../../interfaces/counters-activators.interface';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { CountersActivatorsService } from '../../../../services/counters-activators.service';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
    selector: 'app-related-counters',
    templateUrl: './related-counters.component.html',
    styleUrl: './related-counters.component.css',
    standalone: false
})
export class RelatedCountersComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  counter: CounterDetails | null;
  counters: CountersListItem[];
  relatedCounters: CountersListItem[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _countersActivatorsService: CountersActivatorsService,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<RelatedCountersComponent>,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.counter = null;
    this.counters = [];
    this.relatedCounters = [];
  }

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

  async getCounter(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let counter: CounterDetailsResponse = await lastValueFrom(this._countersActivatorsService.counterConsultOnly(
        this._data.idCounter, 
        idUser, 
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        counter.response.ID_CONTADOR = await this._encService.decrypt(counter.response.ID_CONTADOR);
        
        let codeDec = await this._encService.decrypt(counter.response.CODIGO_EQUIPAMIENTO);
        counter.response.TIPO_EQUIPAMIENTO = `${codeDec} - ${counter.response.TIPO_EQUIPAMIENTO}`;

        let idEquipmentDec = await this._encService.decrypt(counter.response.ID_EQUIPAMIENTO);
        counter.response.MODELO_EQUIPAMIENTO = `${counter.response.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;

        this.counter = counter.response;
        this.getCounters();
      }
    }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 getCounters(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let counters: CountersListResponse = await lastValueFrom(this._countersActivatorsService.counterConsult(idUser, 1));

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

      if(!this.hasError){
        let countersArr: CountersListItem[] = [];
        for(const counter of counters.response){
          counter.ID_CONTADOR = await this._encService.decrypt(counter.ID_CONTADOR);
          countersArr.push(counter);
        }

        let relatedCountersArr = JSON.parse(this.counter!.CONTADORES_VINCULADOS);
        for(const counterEnc of relatedCountersArr){
          let counterDec = await this._encService.decrypt(counterEnc);
          let counterObjFilt = countersArr.filter(counter => counter.ID_CONTADOR == counterDec);

          if(counterObjFilt.length > 0){
            this.relatedCounters.push(counterObjFilt[0]);
          }
        }

        for(const counter of countersArr){
          let counterFilt = this.relatedCounters.filter(item => item.ID_CONTADOR == counter.ID_CONTADOR);
          if(counterFilt.length < 1 && counter.ID_CONTADOR != this.counter!.ID_CONTADOR){
            this.counters.push(counter);
          }
        }
      }

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

  drop(event: CdkDragDrop<CountersListItem[]>){
    if(event.previousContainer === event.container){
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    }else{
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

  async closeRelatedCounters(){
    let countersArr: string[] = [];
    for(const counter of this.relatedCounters){
      let idEnc = await this._encService.encrypt(counter.ID_CONTADOR);
      countersArr.push(idEnc);
    }

    let countersStr = JSON.stringify(countersArr);
    let countersEnc = await this._encService.encrypt(countersStr);

    this._dialogRef.close(countersEnc);
  }
}
