import { Component, Input, OnInit } from '@angular/core';
import { Chart } from 'angular-highcharts';
import * as Highcharts from 'highcharts';

@Component({
  selector: 'byte-tracing-intent-by-customer',
  templateUrl: './tracing-intent-by-customer.component.html',
  styleUrls: ['./tracing-intent-by-customer.component.scss']
})
export class TracingIntentByCustomerComponent implements OnInit {

  chart: Chart;

  @Input()
  minDate: Date;

  @Input()
  maxDate: Date;

  @Input()
  data: any;

  constructor() { }

  ngOnInit() {
    console.log(this.minDate);
    console.log(this.maxDate);
    const series: Array<any> = this.getGenerateData(this.data);
    this.chart = new Chart({
      chart: {
        type: 'line'
      },
      credits: {
        enabled: false
      },
      title: {
        text: ''
      },
      subtitle: {
        text: null
      },
      exporting: {
        enabled: false
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        itemMarginTop: 10,
        itemMarginBottom: 10
      },
      xAxis: {
        type: 'datetime',
        min: this.getDate(this.minDate),
        max: this.getDate(this.maxDate),
        labels: {
          formatter() {
            return Highcharts.dateFormat('%e - %b', this.value * 1000);
          }
        }
      },
      yAxis: {
        title: {
          text: ''
        },
      },
      tooltip: {
        formatter() {
          return '<b>' + this.series.name + '</b><br/>' +
            Highcharts.dateFormat('%e - %b',
              this.x * 1000) +
            ' date, ' + this.y;
        }
      },
      plotOptions: {
        line: {
          marker: {
            enabled: true
          }
        }
      },
      series
    });
  }

  private getGenerateData(data: any): Array<any> {
    const series: Array<any> = [];
    for (const intent in data) {
      if (data.hasOwnProperty(intent)) {
        const serie = {};
        serie['name'] = intent;
        serie['data'] = data[intent];
        series.push(serie);
        console.log(serie);
      }
    }
    return series;
  }

  private getDate(date: Date) {
    console.log(date);
    let dateNumber = date.getTime();
    dateNumber = dateNumber / 1000;
    return Math.trunc(dateNumber);
  }
}
