import { Component, Input, OnDestroy, OnInit } from '@angular/core';

// import { ToogleService } from '@xdf/layouts';
import { Chart } from 'angular-highcharts';
import * as Highcharts from 'highcharts';
import { Subscription } from 'rxjs';

// amCharts imports
import * as am4core from '@amcharts/amcharts4/core';
import * as am4charts from '@amcharts/amcharts4/charts';
import am4themes_animated from '@amcharts/amcharts4/themes/animated';

@Component({
  selector: 'byte-heat-map',
  templateUrl: './heat-map.component.html',
  styleUrls: ['./heat-map.component.scss']
})
export class HeatMapComponent implements OnInit, OnDestroy {

  @Input()
  data: Array<any> = [];

  @Input()
  minDate: Date;

  @Input()
  maxDate: Date;

  subscriptionToogle: Subscription;

  chart: am4charts.XYChart;;

  constructor(
    // protected toogleService: ToogleService
  ) {

  }
  ngOnDestroy(): void {
    if (this.subscriptionToogle) {
      this.subscriptionToogle.unsubscribe();
    }
  }

  ngOnInit() {

    am4core.useTheme(am4themes_animated);
    var colores = new am4core.ColorSet();
    am4core.addLicense("ch-custom-attribution");
    // if (!this.maxDate || !this.minDate) {
    //   console.log(' heat map data : ',this.data);
    //   return;
    // }
    const max_value = this.data.reduce((a,b)=>a[2]>b[2]?a:b)[2];

    const sorted_data = this.data.sort(function(a,b){
      return a[0] < b[0] ? -1:1;
    });

    const dataForDiagram = [];
    sorted_data.forEach(x => {
      // console.log(x[0],x[1],x[2]);
      var date = new Date(x[0] );
      var hours = date.getHours(), year = date.getFullYear(),day = '' + date.getDate(),month = '' + (date.getMonth() + 1);
      var day_local = date.toLocaleDateString('es', { weekday: 'long' });
      var group = 'H' + (x[1] + 1) + ': ' + (3 * x[1] < 10 ? '0' : '') + 3 * x[1] + ':00'
            + ' - ' + ((3 * x[1] + 3) < 10 ? '0' : '') + (3 * x[1] + 3) + ':00';
      // console.log(' date: ',date);  date.toLocaleDateString("es-MX")

      dataForDiagram.push({
        "hour": group,
        "weekday": day+'/'+month,
        "value": x[2]
      });

    });

    var chart = am4core.create("chartdivxx", am4charts.XYChart);
    chart.maskBullets = false;
    chart.paddingRight = 100;
    chart.paddingLeft = 30;

    var xAxis = chart.xAxes.push(new am4charts.CategoryAxis());
    var yAxis = chart.yAxes.push(new am4charts.CategoryAxis());

    xAxis.dataFields.category = "weekday";
    yAxis.dataFields.category = "hour";

    xAxis.renderer.grid.template.disabled = true;
    xAxis.renderer.minGridDistance = 40;

    yAxis.renderer.grid.template.disabled = true;
    yAxis.renderer.inversed = true;
    yAxis.renderer.minGridDistance = 20;

    var series = chart.series.push(new am4charts.ColumnSeries());
    series.dataFields.categoryX = "weekday";
    series.dataFields.categoryY = "hour";
    series.dataFields.value = "value";
    series.sequencedInterpolation = true;
    series.defaultState.transitionDuration = 3000;

    let bgColor = new am4core.InterfaceColorSet().getFor("background");

    var columnTemplate = series.columns.template;
    columnTemplate.strokeWidth = 2;
    columnTemplate.strokeOpacity = 1;
    columnTemplate.stroke = am4core.color("#ffffff");
    columnTemplate.tooltipText = "{weekday}, {hour}: {value.workingValue.formatNumber('#.')} mensajes";
    // El adapter fija colores personalizados
    // columnTemplate.column.adapter.add("fill", function(fill, target) {
    //   if (target.dataItem) {
    //     if (target.dataItem["value"] >= max_value) {
    //       return colores.getIndex(9) 
    //     }
    //     else if (target.dataItem["value"] >= max_value*2/3) {
    //       return colores.getIndex(11)
          
    //     }
    //     else {
    //       return colores.getIndex(12)
          
    //     }
    //   }
    //   return fill;
    // });

    series.heatRules.push({
      target: columnTemplate,
      property: "fill",
      min: colores.getIndex(12),
      max: colores.getIndex(9)
      
    });

    // heat legend
    var heatLegend = chart.bottomAxesContainer.createChild(am4charts.HeatLegend);
    heatLegend.width = am4core.percent(100);
    heatLegend.series = series;
    heatLegend.valueAxis.renderer.labels.template.fontSize = 9;
    heatLegend.valueAxis.renderer.minGridDistance = 30;
    // heatLegend.orientation = "vertical";

    // heat legend behavior
    series.columns.template.events.on("over", (event) => {
      handleHover(event.target);
    })

    series.columns.template.events.on("hit", (event) => {
      handleHover(event.target);
    })

    function handleHover(column) {
      if (!isNaN(column.dataItem.value)) {
        heatLegend.valueAxis.showTooltipAt(column.dataItem.value)
      }
      else {
        heatLegend.valueAxis.hideTooltip();
      }
    }

    series.columns.template.events.on("out", (event) => {
      heatLegend.valueAxis.hideTooltip();
    })

    

    

    // dataForDiagram.push({"hour":"0am","weekday":"Domingo", "value":0 });
    // dataForDiagram.push({"hour":"0am","weekday":"Lunes", "value":0 });
    // dataForDiagram.push({"hour":"0am","weekday":"Domingo", "value":0 });

    // console.log(' heat map data : ',this.data);
    chart.data = dataForDiagram;


    // this.subscriptionToogle = this.toogleService.changeEmitted$.subscribe(change => {
    //   setTimeout(() => {
    //     Highcharts.charts.forEach(chart => chart.reflow());;
    //     console.log("test");
    //   }, 500);
    // });
  }

  ngAfterViewInit(){

    
  }

}
