import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ChartConfiguration, ChartEvent, ChartType } from 'chart.js';
import { EncService } from '../../../../../services/enc.service';
import { CountersActivatorsService } from '../../../../../services/counters-activators.service';
import { FunctionsService } from '../../../../../services/functions.service';
import { SocketService } from '../../../../../services/socket.service';
import { CounterMeasuresListResponse } from '../../../../../interfaces/counters-activators.interface';
import { lastValueFrom } from 'rxjs';

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

  public linearChartData: ChartConfiguration['data'] = {
    datasets: [],
    labels: [],
  };

  public lineChartOptions: ChartConfiguration['options'] = {
    elements: {
      line: {
        tension: 0.5,
      },
    },
    scales: {
      // We use this empty structure as a placeholder for dynamic theming.
      y: {
        position: 'left',
      },
    },

    plugins: {
      legend: { display: true },
      /*annotation: {
        annotations: [
          {
            type: 'line',
            scaleID: 'x',
            value: 'March',
            borderColor: 'orange',
            borderWidth: 2,
            label: {
              display: true,
              position: 'center',
              color: 'orange',
              content: 'LineAnno',
              font: {
                weight: 'bold',
              },
            },
          },
        ],
      },*/
    },
  };

  public lineChartType: ChartType = 'line';

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

  ngOnInit(): void {
    this.init();
    this._socketService.refreshCounterMeasures().subscribe(async (data: any) => {
      let idCounterDec = await this._encService.decrypt(data.idCounter);
      if(idCounterDec == this.idCounter){
        this.getCounterMeasures(data.idCounter);
      }
    })
  }

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

  async getCounterMeasures(idCounterEnc: string | undefined){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idCounter = idCounterEnc == undefined ? this._data.idCounter : idCounterEnc;
      let measures: CounterMeasuresListResponse = await lastValueFrom(this._countersActivatorsService.counterConsultMeasures(
        idCounter, 'FECREG', 'D',
        10, 0, idUser, 1
      ));

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

      if(!this.hasError){
        let measuresVals: number[] = [];
        let labels: string[] = [];

        for(const measure of measures.response){
          measuresVals.push(measure.VALOR);
          labels.push(this._functionsService.getDateTimeHour(measure.HORA_REGISTRO));
        }

        if(idCounterEnc == undefined){
          let colorR = Math.ceil(Math.random() * 255);
          let colorG = Math.ceil(Math.random() * 255);
          let colorB = Math.ceil(Math.random() * 255);
      
          let dataset = {
            data: measuresVals,
            label: 'Mediciones',
            backgroundColor: `rgba(${colorR},${colorG},${colorB},0.2)`,
            borderColor: `rgba(${colorR},${colorG},${colorB},1)`,
            pointBackgroundColor: `rgba(${colorR},${colorG},${colorB},1)`,
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: `rgba(${colorR},${colorG},${colorB},0.8)`,
            fill: 'origin',
          };
  
          this.linearChartData.datasets = [dataset];
          this.linearChartData.labels = labels;
        }else{
          let backgroundColor = this.linearChartData.datasets[0].backgroundColor;
          let borderColor = this.linearChartData.datasets[0].borderColor;
          let pointBackgroundColor = this.linearChartData.datasets[0].borderColor;
          let pointHoverBorderColor = this.linearChartData.datasets[0].borderColor!.toString().replace(',1)', ',0.8)');
      
          let dataset = {
            data: measuresVals,
            label: 'Mediciones',
            backgroundColor: backgroundColor!.toString(),
            borderColor: borderColor!.toString(),
            pointBackgroundColor: pointBackgroundColor!.toString(),
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: pointHoverBorderColor,
            fill: 'origin',
          };

          this.linearChartData = {
            datasets: [dataset],
            labels: labels
          }
        }
      }

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

  public chartHovered({
    event,
    active,
  }: {
    event?: ChartEvent;
    active?: object[];
  }): void {
    //console.log(event, active);
  }

  // events
  public chartClicked({
    event,
    active,
  }: {
    event?: ChartEvent;
    active?: object[];
  }): void {
    //console.log(event, active);
  }
}
