import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { CounterLastMeasuresListItem, CounterMeasuresListResponse } from '../../../../../interfaces/counters-activators.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../../services/enc.service';
import { CountersActivatorsService } from '../../../../../services/counters-activators.service';
import { FunctionsService } from '../../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';

@Component({
    selector: 'app-measures-history',
    templateUrl: './measures-history.component.html',
    styleUrl: './measures-history.component.css',
    standalone: false
})
export class MeasuresHistoryComponent implements OnInit, AfterViewInit {
  idCounter: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  displayedColumns = ['ID_MEDIDA', 'VALOR', 'WEB_SERVICE', 'FECREG'];
  dataSource: MatTableDataSource<CounterLastMeasuresListItem>;
  dataLength: number;

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

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _functionsService: FunctionsService,
  ) {
    this.idCounter = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.dataSource = new MatTableDataSource();
    this.dataLength = 0;
  }

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

  ngAfterViewInit(): void {
    this.sort!.sortChange.subscribe(() => {
      this.paginator!.pageIndex = 0;
      this.getCounterMeasuresLength();
    });

    this.paginator!.page.subscribe(() => {
      this.getCounterMeasuresLength();
    });
  }

  async init(){
    this.idCounter = await this._encService.decrypt(this._data.idCounter);
    this.getCounterMeasuresLength();
  }

  async getCounterMeasuresLength(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let measuresLength = await lastValueFrom(this._countersActivatorsService.counterConsultMeasuresLength(
        this._data.idCounter,
        idUser,
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        this.dataLength = measuresLength.response.MEASURES_LENGTH;
        
        this.getCounterMeasures();
      }
    }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;
    }
  }

  async getCounterMeasures(){
    try{
      let sort = this.sort.active;
      let direction = this.sort!.direction == 'desc' ? 'D' : 'A';
      let offset = this.paginator!.pageIndex * 10;

      let idUser = localStorage.getItem('idusuario')!;
      let measures: CounterMeasuresListResponse = await lastValueFrom(this._countersActivatorsService.counterConsultMeasures(
        this._data.idCounter,
        sort == undefined ? 'ID_MEDIDA' : sort,
        direction,
        10,
        offset,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let measuresArr: CounterLastMeasuresListItem[] = [];
        for(const measure of measures.response){
          let idDec = await this._encService.decrypt(measure.ID_MEDIDA);
          let idSWDec = await this._encService.decrypt(measure.ID_SERVICIO_WEB);

          measure.ID_MEDIDA = idDec;
          measure.URL_SERVICIO_WEB = `${measure.URL_SERVICIO_WEB} (${idSWDec})`;
          measure.HORA_REGISTRO = this._functionsService.orderDate(measure.HORA_REGISTRO)!;

          measuresArr.push(measure);
        }

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

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

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