import { AfterViewInit, Component, HostListener, Input, OnChanges, OnInit, ViewChild } from '@angular/core';
import { PeityComponent } from '@xdf/graph';
import { PetiFormatter } from './formatter/formatter';

import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import { random } from '@amcharts/amcharts4/.internal/core/utils/String';

import am4lang_es_ES from "@amcharts/amcharts4/lang/es_ES";
import { TranslateService } from '@ngx-translate/core';

declare var jQuery: any;

export class PetyWidgetModel {
  percent: number;
  up?: boolean;
  down?: boolean;
  value: number;
  history: Array<number>;
}

@Component({
  selector: 'byte-summary-peti-widget',
  templateUrl: './summary-peti-widget.component.html',
  styleUrls: ['./summary-peti-widget.component.scss']
})
export class SummaryPetiWidgetComponent implements OnInit, AfterViewInit {

  @Input() options = {
    width: 200,
    height: 60,
    fill: '#dfecf9',
    stroke: '#024990',
    strokeWidth: 1
  };
  @Input() values = [1, 12, 3, 15, 5, -1, 10];
  @Input() header;
  @Input() value: PetyWidgetModel;
  @Input() tooltip: string;
  @Input() formatter: PetiFormatter;
  monthList: string[] = ["month_jan", "month_feb", "month_mar", "month_apr","month_may", "month_jun","month_jul","month_aug","month_sept","month_oct","month_nov","month_dec"];
  @Input() StartDate : Date;
  @Input() EndDate: Date;

  @Input() areaColor;

  @Input() identificador: string;
  
  chart: am4charts.XYChart;

  @ViewChild('peti', { static: false })
  peti: PeityComponent;

  constructor(
    private translate: TranslateService,
  ) { }

  ngOnInit() {
    
  }

  FiltradorFecha(lista:any[],start:Date,final:Date):any[]{
    var newList: any[] = []
    lista.forEach(x=>{
      
      if(x["date"]>start && x["date"]<final){
   
        newList.push({
          date:x["date"],
          value:x["value"]
        });
      }
    });
    return newList
  }

  randomIntFromInterval(min, max) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min)
  }

  randomDate(start, end, startHour, endHour) {
    var date = new Date(+start + Math.random() * (end - start));
    var hour = startHour + Math.random() * (endHour - startHour) | 0;
    date.setHours(hour);
    return date;
  }

//   const generateRandomDOB = (): string => {
//     const random = this.getRandomDate(new Date('1950-02-12T01:57:45.271Z'), new Date('2001-02-12T01:57:45.271Z'))
//     return random.toISOString();
// }

getRandomDate(from: Date, to: Date) {
    const fromTime = from.getTime();
    const toTime = to.getTime();
    return new Date(fromTime + Math.random() * (toTime - fromTime));
}

  randomizer(): any[] {
    var newList: any[] = []
    var b=  new Date(2021,12,25,17, 23, 42)
      var a=  new Date(2021,1,1,17, 23, 42)
    for(var i=0;i<100;i++){  
      newList.push({
        date: this.getRandomDate(a,b),
        value:this.randomIntFromInterval(0,12)
      });
    }
    return newList
  }

   getDifferenceInDays(date1, date2) {
    const diffInMs = Math.abs(date2 - date1);
    return diffInMs / (1000 * 60 * 60 * 24);
  }

  getDifferenceInHours(date1,date2){
    const diffInMs = Math.abs(date2 - date1);
    return Math.floor((diffInMs % 86400000) / 3600000);
  }

  

  orderlist(lista:any[]):any[]{
    
    for(var i=0;i<lista.length;i++){  
      for(var j=0;j<lista.length-2;j++){  
        if(lista[j]["date"]>lista[j+1]["date"]){
          var a = lista[j]
          lista[j]=lista[j+1]
          lista[j+1]=a
        }
      }
    }
    
    return lista
  }


  // ngOnChanges(){
  //   const dataForChart = [];
  //   const sorted_data = this.value.history.sort(function(a,b){
  //     return a[0] < b[0] ? -1:1;
  //   });
  //   let isDataDates = true;
  //   sorted_data.forEach(x => {
  //     if (typeof(x[0]) == 'string' ){
  //       const date = x[0];
  //       dataForChart.push({
  //         "date": date,
  //         "value": x[1]
  //       });
  //       isDataDates = false;
  //     }
  //     else{
  //       const date = new Date(x[0]);
  //       dataForChart.push({
  //         "date": date,
  //         "value": x[1]
  //       });
  //     }
  //   });
  //   this.chart.data=this.FiltradorFecha(dataForChart,this.StartDate,this.EndDate)

  // }

  ngAfterViewInit() {
    var starDate = new Date(2021,2,1,17, 23, 42); 
    var finalDate = new Date(2021,10,25,17, 23, 42); 
    if(this.EndDate){
      finalDate= this.EndDate as Date
      starDate = this.StartDate as Date
    }
    
   
    
     this.chart = am4core.create(this.identificador, am4charts.XYChart);
     this.chart.language.locale = am4lang_es_ES;
    var colors = new am4core.ColorSet();
    // chart.width = am4core.percent(100);
    // chart.height = 70;

    const dataForChart = [];

    const sorted_data = this.value.history.sort(function(a,b){
      return a[0] < b[0] ? -1:1;
    });
    let isDataDates = true;
    sorted_data.forEach(x => {
      if (typeof(x[0]) == 'string' ){
        const date = x[0];
        dataForChart.push({
          "date": date,
          "value": x[1]
        });
        isDataDates = false;
      }
      else{
        const date = new Date(x[0]);
        dataForChart.push({
          "date": date,
          "value": x[1],
          "month": this.translate.instant(this.monthList[date.getMonth()]),
          "hour": date.getHours(),
          "minute": date.getMinutes() == 0 ? '00' : date.getMinutes()
        });
      }
      // console.log(new Date(x[0]))
      // console.log(new Date(x[0]).getHours());
      // console.log('MINUTES')
      // console.log(new Date(x[0]).getMinutes())
      // console.log(new Date(x[0]).getMonth());
    });

    console.log(dataForChart);
    

    // console.log(dataForChart)
    // console.log(this.FiltradorFecha(dataForChart,starDate,finalDate))
    //var a = this.orderlist(this.randomizer())

    this.chart.data = dataForChart; //this.FiltradorFecha(a,starDate,finalDate)
    // console.log(dataForChart)

    // chart.titles.template.fontSize = 10;
    // //chart.titles.template.textAlign = "left";
    // chart.titles.template.isMeasured = false;
    // chart.titles.create().text = "AAPL (Price)";

    this.chart.padding(30, 15, 2, 5);

    if (isDataDates){
      var dateAxis = this.chart.xAxes.push(new am4charts.DateAxis());
      // dateAxis.renderer.grid.template.disabled = true;
      // dateAxis.renderer.labels.template.disabled = true;
      // dateAxis.startLocation = 0.5;
      // dateAxis.endLocation = 0.7;
      dateAxis.cursorTooltipEnabled = false;
      
      

      //agrupar informacion
       dateAxis.groupData=true;


//       dateAxis.startLocation = 0;
// dateAxis.endLocation = 0;
      // dateAxis.zoomToDates(starDate,finalDate);
      dateAxis.verticalCenter = "bottom"
      dateAxis.horizontalCenter = "left"
      
      dateAxis.renderer.cellStartLocation=0.5
     
      
      
      

      

      dateAxis.renderer.labels.template.rotation = 270;
      // dateAxis.renderer.minLabelPosition = 0.0;
       dateAxis.renderer.maxLabelPosition = 0.95;
      
      // dateAxis.renderer.labels.template.rotation = 90;
      // dateAxis.renderer.labels.template.verticalCenter = "middle";
      // dateAxis.renderer.labels.template.horizontalCenter = "left";
      // dateAxis.title.text = "Fecha";

      var valueAxis = this.chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.min = 0;
      // valueAxis.renderer.grid.template.disabled = true;
      // valueAxis.renderer.baseGrid.disabled = true;
      // valueAxis.renderer.labels.template.disabled = true;
      valueAxis.cursorTooltipEnabled = false;
      valueAxis.title.text = "Total";
      valueAxis.renderer.labels.template.adapter.add("text", function(text) {
        return text;
      });

      this.chart.cursor = new am4charts.XYCursor();
      // chart.cursor.lineY.disabled = true;
      this.chart.cursor.behavior = "none";

      var series = this.chart.series.push(new am4charts.LineSeries());
      
      // series.tooltipHTML = "<img src='https://www.amcharts.com/lib/3/images/bicycle.png' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>{date}: [bold]{value}</b></span>";
      series.dataFields.dateX = "date";
      series.dataFields.valueY = "value";
      series.fillOpacity = 0.6;
      series.tensionX = 0.8;
      series.strokeWidth = 2;
      series.stroke = colors.getIndex(this.areaColor);
      series.fill = series.stroke;
      // series.groupFields.openValueY = "open"
      series.groupFields.valueY = "sum";
      
      if( this.getDifferenceInDays(this.StartDate,this.EndDate) > 30){
        dateAxis.groupIntervals.setAll([
          { timeUnit: "month", count: 1 }
         ]);
         dateAxis.startLocation = 0.5;
         dateAxis.endLocation = 0.5;
         dateAxis.renderer.minGridDistance = 1;
         series.tooltipText = "{month}: [bold]{valueY}";
         
   
      }
      else if(this.getDifferenceInDays(this.StartDate,this.EndDate) < 1){
        if(this.getDifferenceInHours(this.StartDate,this.EndDate)>2){
          dateAxis.groupIntervals.setAll([
            { timeUnit: "hour", count: 2 }
           ]);
           dateAxis.startLocation = 0;
           dateAxis.endLocation = 1;
           dateAxis.renderer.minGridDistance = 15;
           series.tooltipText = "{hour}:{minute} : [bold]{valueY}";
        }
        else if (this.getDifferenceInHours(this.StartDate,this.EndDate)>0.8){
          dateAxis.groupIntervals.setAll([
            { timeUnit: "minute", count: 5 }
           ]);
           dateAxis.startLocation = 0.1;
           dateAxis.endLocation = 1;
           dateAxis.renderer.minGridDistance = 15;
           series.tooltipText = "{hour}:{minute} : [bold]{valueY}";
        }
        else{
          dateAxis.groupIntervals.setAll([
            { timeUnit: "minute", count: 1 }
           ]);
           dateAxis.startLocation = 0.1;
           dateAxis.endLocation = 1;
           dateAxis.renderer.minGridDistance = 5;
           series.tooltipText = "{hour}:{minute} : [bold]{valueY}";
        }
        // console.log('CASO A')
        
      }
      else{
        dateAxis.groupIntervals.setAll([
          
          { timeUnit: "day", count: 1 }
          
         ]);
         dateAxis.startLocation = 0.5;
         dateAxis.endLocation = 0.5;
         dateAxis.renderer.minGridDistance = 200;
         series.tooltipText = "{date}: [bold]{valueY}";
      }

      
      
     

      // render data points as bullets
      var bullet = series.bullets.push(new am4charts.CircleBullet());
      bullet.circle.opacity = 0;
      bullet.circle.fill = colors.getIndex(this.areaColor);
      bullet.circle.propertyFields.opacity = "opacity";
      bullet.circle.radius = 3;
    }
    else{
      var categoryAxis1 = this.chart.xAxes.push(new am4charts.CategoryAxis());
      categoryAxis1.dataFields.category = "date";
      // categoryAxis1.renderer.labels.template.disabled = true;
      categoryAxis1.renderer.labels.template.adapter.add("text", function(text) {
        return '';
      });

      var valueAxis = this.chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.min = 0;
      // valueAxis.renderer.grid.template.disabled = true;
      // valueAxis.renderer.baseGrid.disabled = true;
      // valueAxis.renderer.labels.template.disabled = true;
      valueAxis.cursorTooltipEnabled = false;
      valueAxis.title.text = "Total";
      valueAxis.renderer.labels.template.adapter.add("text", function(text) {
        return text;
      });

      

      this.chart.cursor = new am4charts.XYCursor();
      // chart.cursor.lineY.disabled = true;
      this.chart.cursor.behavior = "none";

      var series = this.chart.series.push(new am4charts.LineSeries());
      series.tooltipText = "{date}: [bold]{value}";
      // series.tooltipHTML = "<img src='https://www.amcharts.com/lib/3/images/bicycle.png' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>{date}: [bold]{value}</b></span>";
      series.dataFields.categoryX = "date";
      series.dataFields.valueY = "value";
      series.fillOpacity = 0.6;
      series.tensionX = 0.8;
      series.strokeWidth = 2;
      series.stroke = colors.getIndex(this.areaColor);
      series.fill = series.stroke;

      // render data points as bullets
      var bullet = series.bullets.push(new am4charts.CircleBullet());
      bullet.circle.opacity = 0;
      bullet.circle.fill = colors.getIndex(this.areaColor);
      bullet.circle.propertyFields.opacity = "opacity";
      bullet.circle.radius = 3;
    }

    

    
  }

  get formatterValue(): string|number {
    if (this.formatter) {
      return this.formatter.format(this.value.value);
    }
    return this.value.value;
  }

  @HostListener('window:resize', ['$event'])
  public onResize(event) {
    const width = event.target.innerWidth;
    this.updateWidth(width);
    
  }

  private updateWidth(width: number) {
    if (width >= 1600) {
      this.options.width = 300;
    } else if (width >= 1350) {
      this.options.width = 200;
    } else if (width >= 768) {
      this.options.width = 150;
    } else if (width >= 576) {
      this.options.width = 200;
    } else {
      this.options.width = 300;
    }
  }

}