import { Component, Input, OnInit, Inject, NgZone, PLATFORM_ID  } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Chart } from 'angular-highcharts';

// 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-sankey-diagram',
  templateUrl: './sankey-diagram.component.html',
  styleUrls: ['./sankey-diagram.component.scss']
})
export class SankeyDiagramComponent implements OnInit {

  chart: am4charts.XYChart;
  startPoint = 'Session start';
  private percentDetail = {};

  @Input()
  data;

  constructor(@Inject(PLATFORM_ID) private platformId, private zone: NgZone) {}


  // Run the function only in the browser
  browserOnly(f: () => void) {
    if (isPlatformBrowser(this.platformId)) {
      this.zone.runOutsideAngular(() => {
        f();
      });
    }
  }

  ngAfterViewInit() {
    // Chart code goes in here
    this.browserOnly(() => {
      am4core.useTheme(am4themes_animated);

      let chart = am4core.create("chartdiv", am4charts.XYChart);

      chart.paddingRight = 20;

      let data = [];
      let visits = 10;
      for (let i = 1; i < 366; i++) {
        visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
        data.push({ date: new Date(2018, 0, i), name: "name" + i, value: visits });
      }

      chart.data = data;

      let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
      dateAxis.renderer.grid.template.location = 0;

      let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.tooltip.disabled = true;
      valueAxis.renderer.minWidth = 35;

      let series = chart.series.push(new am4charts.LineSeries());
      series.dataFields.dateX = "date";
      series.dataFields.valueY = "value";
      series.tooltipText = "{valueY.value}";

      chart.cursor = new am4charts.XYCursor();

      let scrollbarX = new am4charts.XYChartScrollbar();
      scrollbarX.series.push(series);
      chart.scrollbarX = scrollbarX;

      this.chart = chart;
    });
  }

  ngOnDestroy() {
    // Clean up chart when the component is removed
    this.browserOnly(() => {
      if (this.chart) {
        this.chart.dispose();
      }
    });
  }

  ngOnInit() {
    if (!this.data) {
      return;
    }
    // console.log('Sankey data ',this.data);
    const dataDiagram = this.generateData(this.data);
    if (!dataDiagram) {
      return;
    }
    
  }

  private generateData(data: any) {
    if (!data['topList']) {
      return undefined;
    }
    const dataForDiagram = [];
    data['topList'].forEach(x => {
      // PercentageInventary.getInstance().setPercent(x['identifier'], x['count']/data['total']*100);
      dataForDiagram.push([this.startPoint, x['identifier'], x['count']]);
    });
    return dataForDiagram;
  }

}

function update(key) {
  return PercentageInventary.getInstance().getPercent(key);
}

export class PercentageInventary {

  private static instance: PercentageInventary;
  private percentages: any = {};

  public static getInstance(): PercentageInventary {
    if (!PercentageInventary.instance) {
      PercentageInventary.instance = new PercentageInventary();
    }

    return PercentageInventary.instance;
  }

  getPercent(name: string) {
    if (this.percentages[name]) {
      return (this.percentages[name] as number).toFixed(2) + '%';
    }
    return null;
  }

  setPercent(name: string, value: any) {
    this.percentages[name] = value;
  }
}
