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

import { Chart } from 'angular-highcharts';

@Component({
  selector: 'byte-sankey-diagram',
  templateUrl: './sankey-diagram.component.html',
  styleUrls: ['./sankey-diagram.component.scss']
})
export class SankeyDiagramComponent implements OnInit {

  chart: Chart;
  startPoint = 'Session start';
  private percentDetail = {};

  @Input()
  data;

  constructor() { }

  ngOnInit() {
    if (!this.data) {
      return;
    }
    const dataDiagram = this.generateData(this.data);
    if (!dataDiagram) {
      return;
    }
    this.chart = new Chart({
      title: {
          text: ''
      },
      exporting: {
        enabled: false
      },
      chart: {
        marginTop: 30
      },
      credits: {
        enabled: false
      },
      accessibility: {
          point: {
              valueDescriptionFormat: '{index}. {point.from} to {point.to}, {point.weight}.'
          }
      },
      // tooltip: {
      //   formatter: function() {
      //     return update(this.key);
      //   }
      // },
      series: [{
        marker: {
          symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
        },
          lineWidth: 5,
          keys: ['from', 'to', 'weight'],
          data: dataDiagram,
          type: 'sankey',
          name: 'Intenciones',
          // dataLabels: {
          //   formatter: function () {
          //     console.log(this);
          //     return '';
          //   }
          // },
      }] as Array<any>
    });
  }

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