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.SankeyDiagram);

      chart.data = [
        { from: 'Session Start', to: 'Book Hotel', value: 29.9 },
        { from: 'Session Start', to: 'Rent Car', value: 16.5 },
        { from: 'Session Start', to: 'Help', value: 8.1 },
        { from: 'Session Start', to: "Others", value: 35 },
        { from: 'Session Start', to: "Feedback", value: 3.1 },
        { from: 'Session Start', to: "Greets", value: 5 },
        { from: 'Session Start', to: "Payment", value: 2 }
      ];
      chart.nodes.template.nameLabel.label.truncate = false;
      chart.nodes.template.nameLabel.label.wrap = true;

      chart.dataFields.fromName = "from";
      chart.dataFields.toName = "to";
      chart.dataFields.value = "value";
      chart.paddingRight = 100;
      chart.paddingLeft = 30;
      chart.paddingTop    = 100;
      chart.paddingBottom = 100;


      var nodeTemplate = chart.nodes.template;
      nodeTemplate.width = 100;
      // texto dentro de la caja
      nodeTemplate.nameLabel.locationX = 0.2;
      // nodeTemplate.minHeight
      nodeTemplate.showTooltipOn  = "hover";
      nodeTemplate.tooltipText =  `
      {fromName} → {toName}: [bold]{value}[/] \n \n
      [bold]Ayuda
      (Contenido del mensaje) \n \n
      %[/] de todos los mensajes 
      {value} %[/]\n \n
      Número de mensajes
      {value}
      `;
      nodeTemplate.cursorOverStyle = am4core.MouseCursorStyle.pointer;
      nodeTemplate.stroke = am4core.color("#fff");
      nodeTemplate.strokeWidth = 2;
      nodeTemplate.nameLabel.locationX = 0.1;
      nodeTemplate.nameLabel.label.fill = am4core.color("#fff");
      nodeTemplate.nameLabel.label.fontWeight = "bold";
      nodeTemplate.fontSize = 12;
      nodeTemplate.nameLabel.label.width = 150;
      nodeTemplate.width = 100;
      nodeTemplate.minHeight  = 50;
      nodeTemplate.maxHeight  = 50;
      // nodeTemplate.measuredHeight = 10;
      nodeTemplate.height = 10;
      nodeTemplate.paddingBottom = 10;
      nodeTemplate.marginBottom = 300;
      nodeTemplate.margin(0, 0, 0, 0);


      var linkTemplate = chart.links.template;
      linkTemplate.tooltipText = `
        {fromName} → {toName}: [bold]{value}[/] \n \n
        [bold]Ayuda
        (Contenido del mensaje) \n \n
        %[/] de todos los mensajes 
        {value} %[/]\n \n
        Número de mensajes
        {value}
      `;
      linkTemplate.minHeight = 30;
      linkTemplate.tension = 0.6;
      var hoverState = linkTemplate.states.create("hover");
      hoverState.properties.fillOpacity = 1;
      linkTemplate.controlPointDistance = 0.1;
      linkTemplate.fill = am4core.color("#A8C686");
      
    });
  }

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