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()
  identificador;

  @Input()
  data;

  prefix_intent = 'intencion_';

  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);
      am4core.addLicense("ch-custom-attribution");

      let chart = am4core.create(this.identificador, am4charts.SankeyDiagram);
      var datasankey =this.generateData(this.data);
      // console.log(this.agrupador(datasankey))
      
      //funcion agrupadora de datos
      datasankey = this.ordenar(datasankey)
      
      chart.data = this.agrupador(datasankey)
      chart.nodes.template.nameLabel.label.truncate = false;
      chart.nodes.template.nameLabel.label.wrap = true;
           
      // espacio entre nodos
      chart.nodePadding = 50;

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


      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 =  `
      // [bold]{to}[/]   \n \n
      // Número de mensajes
      // {value} \n \n
      // Porcentaje del total de mensajes 
      // {percent} %[/]
      // `;
      nodeTemplate.clickable =false;
      nodeTemplate.draggable=false;

      if(this.identificador.toString()=="sankeyIntent"){
        
        nodeTemplate.tooltipHTML = `
        <div class="row" style="text-align-last:left">
          <div class="col-8" style="color: #49464c;margin-bottom:10px">
            <div></div>
            <strong>
            Intencion: {to}
            </strong>          
          </div>
        </div>
        
        <div class="row" style="text-align-last:left;color: #9c9c9c;font-size:12px;">
          <div class="col-8">
          <i class="fa fa-sort-numeric-asc"></i>
            Número de mensajes:
          </div>
          <div class="col-1">
            {value}
          </div>
        </div>
        <div class="row" style="text-align-last:left;color: #9c9c9c;font-size:12px;">
          <div class="col-8">
          <i class="fa fa-slack"></i>
          Porcentaje del total de mensajes:
          </div>
          <div class="col-1">
            {percent} %
          </div>
        </div>
  `;
      }else {
        nodeTemplate.tooltipHTML = `
        <div class="row" style="text-align-last:left">
          <div class="col-8" style="color: #49464c;">
            <div></div>
            <strong>
            Frase: {to}
            </strong>          
          </div>
        </div>
        
        <div class="row" style="text-align-last:left;color: #9c9c9c;font-size:12px;">
          <div class="col-9">
          <i class="fa fa-sort-numeric-asc"></i>
            Número de mensajes:
          </div>
          <div class="col-1">
            {value}
          </div>
        </div>
        <div class="row" style="text-align-last:left;color: #9c9c9c;font-size:12px;">
          <div class="col-9">
          <i class="fa fa-slack"></i>
          Porcentaje del total de mensajes:
          </div>
          <div class="col-1">
            {percent} %
          </div>
        </div>
  `;
      }
      
      


      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.nameLabel.label.truncate =false;
      nodeTemplate.nameLabel.label.wrap =true;
      
      
      

      

      nodeTemplate.nameLabel.label.hideOversized = false;
      



      // nodeTemplate.nameLabel.label.propertyFields={
      //   hideOversized : "true",
        
      // }
     
      nodeTemplate.fontSize = 12;
      
      var colores = new am4core.ColorSet();

      chart.tooltip.getFillFromObject = false;
      // chart.tooltip.text.fontcolor("#000000") 
      chart.tooltip.label.fill = am4core.color("#000000");
      
      chart.tooltip.background.fill = am4core.color("#f3f3f4");
      // colores.getIndex(1)

      // var a = chart.tooltip.background.fill
      // nodeTemplate.tooltip.background.fill=am4core.color("#67b7dc");
      // chart.tooltip.background.adapter.add( "fill", function(fill,target) {
      //   return am4core.color("#67b7dc");
      // }
      // );

      nodeTemplate.nameLabel.label.adapter.add("text", function(text, target) {
      
        if (target.currentText!=undefined) {
          if(target.currentText=="Session start"){
            return target.currentText
          }
          else {
            if (target.currentText.length >= 10) {
              var a=target.currentText.slice(0,10)
              return a +"..."
            }
            else {
              return target.currentText
            }
          }
            
        
      }
      return text;
    },1000);

    nodeTemplate.adapter.add("tooltipHTML",function(tooltipHTML,target,){
      // console.log(target.dataItem)
      // return tooltipHTML
      if(target.nameLabel.label.currentText=="Session start" ){
        
        return undefined
      }
      else  {
        
      return tooltipHTML
      }
    })
      
      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 
      //   {percent} %[/]\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");

      linkTemplate.adapter.add("tooltipHTML",function(tooltipHTML,target){
        console.log(tooltipHTML)
        // target.tooltipX=200
        // target.tooltipY=600
        return `
            <div class="row" style="text-align-last:left;width:auto">
              <div class="col-8" style="color: #49464c;">
                {from}
              -> {to} 
              </div>
            </div>
          `
      })

      // {{ (element.identifier.length>50)? (element.identifier | slice:0:30)+'...':(element.identifier) }}
      
    });
  }

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

  private agrupador(datosankey:any[]):any[]{
    if(datosankey.length >5){
      var listanueva:any[] = [];
      var contador = 5
      var percentR =0.00
      var valueR =0
      datosankey.forEach(x => {
        if(contador!=0){
          listanueva.push({
            from: x['from'],
            to: x['to'],
            to_short: x['to_short'],
            percent: x['percent'],
            value: x['value']
          });
          contador--
        }
        else{
          percentR += parseFloat( x['percent'])
          valueR += x['value']
        }
      }
      )

      listanueva.push({
        from: "Session start",
        to: "Otros",
        to_short: "Otros",
        percent: percentR.toFixed(2),
        value: valueR
      })
      return  listanueva
    }
    else return  datosankey
  }

  private ordenar(datosankey:any[]):any[]{
    for(var i=datosankey.length;i>0;i--){
      for(var j=0;j<i-1;j++){
        if(datosankey[j]['value']<datosankey[j+1]['value']){
          var temp=datosankey[j]
          datosankey[j]=datosankey[j+1]
          datosankey[j+1]=temp
        }
      }
    }
    for(var i=0;i<datosankey.length;i++){
      if(datosankey[i]['to']=='others'){
        var others = datosankey.splice(i,1);
        datosankey.push(others[0]);
      }
    }
    return datosankey
  }

  ngOnInit() {
    // console.log(' id sankey :',this.identificador,this.data);
    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({
        from:this.startPoint, 
        to: x['identifier'], 
        value: x['count']});
    });
    let total_cont = 0;
    dataForDiagram.forEach(x => {
      total_cont = total_cont + x['value'];
    });
    const columnsData = [];
    dataForDiagram.forEach(x => {
      
      let long_label = x['to'];
      
      if (x['to'].includes(this.prefix_intent)){
        long_label = x['to'].split(this.prefix_intent)[1];
      }
      if (x['to'].includes('intenccion_')){
        long_label = x['to'].split('intenccion_')[1];
      }
      let short_label = long_label.substring(0,6);
      if (x['to'].length > 6){
        short_label = short_label +'...';
      }
      columnsData.push({
        from: x['from'],
        to: long_label,
        to_short: short_label,
        value: x['value'],
        percent: (x['value']/total_cont*100).toFixed(2)
      });
    });
    // columnsData[0]['to_short'] = this.startPoint;
    // console.log(columnsData);

    return columnsData;
  }

}

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