import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { CountersListItem, CountersListResponse } from 'src/app/interfaces/counters-activators.interface';
import { CountersActivatorsService } from 'src/app/services/counters-activators.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { CounterDetailsComponent } from './counter-details/counter-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { RelatedCountersComponent } from './related-counters/related-counters.component';

@Component({
  selector: 'app-counters-management',
  templateUrl: './counters-management.component.html',
  styleUrls: ['./counters-management.component.css']
})
export class CountersManagementComponent implements OnInit {
  public txtBuscador:string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  dataSource: MatTableDataSource<CountersListItem>;
  displayedColumns = ['ID', 'SCADA', 'EQUIPAMIENTO', 'ACCIONES'];

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) {
    this.txtBuscador = '';

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.dataSource = new MatTableDataSource();
  }

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

  public onResize(): void {
    
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  async openCounterForm(type: string, idCounter: string = '-'){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    this._router.navigate([`sam/COAC/CONT/GECO/${type}`], {
      queryParams: {
        idCounter: idCounterEnc
      }
    })
  }

  async getCounters(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      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){
          let idCountDec = await this._encService.decrypt(counter.ID_CONTADOR);
          counter.ID_CONTADOR = idCountDec;

          let idSCADADec = await this._encService.decrypt(counter.ID_SCADA);
          counter.SCADA = `${counter.SCADA} (${idSCADADec})`;

          let codeDec = await this._encService.decrypt(counter.CODIGO_EQUIPAMIENTO);
          counter.TIPO_EQUIPAMIENTO = `${codeDec} - ${counter.TIPO_EQUIPAMIENTO}`;

          let idEquipmentDec = await this._encService.decrypt(counter.ID_EQUIPAMIENTO);
          counter.MODELO_EQUIPAMIENTO = `${counter.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;
          
          if(counter.ESTADO == 'Activo'){
            countersArr.push(counter);
          }
        }

        this.dataSource = new MatTableDataSource(countersArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

      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 openCounterDetails(idCounter: string){
    let counterFilt = this.dataSource.data.filter(item => item.ID_CONTADOR == idCounter);
    if(counterFilt.length < 1){
      this._resourcesService.openSnackBar(`El contador #${idCounter} no existe.`);
      return;
    }
    
    let idCounterEnc = await this._encService.encrypt(idCounter);
    this._dialog.open(CounterDetailsComponent, {
      width: '540px',
      data: {
        idCounter: idCounterEnc,
        includeActivator: counterFilt[0].TIENE_ACTIVADOR,
        idActivator: counterFilt[0].ACTIVADOR,
      }
    })
  }

  async openConfirmDialog(idCounter: string){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: '¿Está seguro de continuar con la eliminación del registro?',
        description2: 'Esta acción no se puede deshacer'
      }
    });

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

  private async deleteCounter(idCounterEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_counter', idCounterEnc);

      await lastValueFrom(this._countersActivatorsService.counterDelete(formData));

      this._resourcesService.openSnackBar('El contador se eliminó correctamente.');
      this.getCounters();
    }catch(error: any){
      if(error.error.msg == 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('Ocurrió un error inesperado.');
      }
    }
  }

  async openRelatedCounters(idCounter: string){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    let dialogRef = this._dialog.open(RelatedCountersComponent, {
      width: '840px',
      data: {
        idCounter: idCounterEnc
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        this.saveRelatedCounters(idCounter, res);
      }
    });
  }

  private async saveRelatedCounters(idCounter: string, dataEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataDec = await this._encService.decrypt(dataEnc);
      let idCounterEnc = await this._encService.encrypt(idCounter);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_counter', idCounterEnc);
      formData.append('related_counters', dataDec);

      await lastValueFrom(this._countersActivatorsService.relateCounters(formData));

      this._resourcesService.openSnackBar('La vinculación del contador se realizó correctamente.');
      this.getCounters();
    }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);
      }
    }
  }
}
