import { AfterViewChecked, AfterViewInit, Component, Directive, ElementRef, EventEmitter, Inject, Input, OnInit, Output, ViewChild } from '@angular/core';

import { Observable, Subscription } from 'rxjs/Rx';

import { MAT_DIALOG_DATA, MatDialog, MatDialogRef, MatExpansionPanel, MatGridTile } from '@angular/material';

import { AbstractControl } from '@angular/forms';

import { animate, state, style, transition, trigger } from '@angular/animations';
import { AccountService, IKnokOngoingData, IOngoingKnok, KnokService } from '../../shared';

import { Chart } from 'chart.js';

@Component({
    selector: 'knk-ex-ongoing-item',
    styleUrls: ['./ongoingitem.component.scss'],
    templateUrl: './ongoingitem.component.html'
})
export class ExOngoingItemComponent implements OnInit {
    @Input('item') item: IKnokOngoingData;
    @Output() changedItem: EventEmitter<void> = new EventEmitter<void>();

    chart: Chart;
    @ViewChild('canvas') canvas;

    timeLeft: string;

    constructor(public dialog: MatDialog) {
    }

    initChart(): void {
      const oneDayTiks: number = (24 * 60 * 60 * 1000);
      let pointBackgroundColorData: Array<string> = [];
      let pointBorderColorData: Array<string> = [];

      let currDate: Date = new Date();
      // currDate = new Date(`${currDate.getMonth() + 1}/${currDate.getDate()}/${currDate.getFullYear()}`);
      const endDate: Date = new Date(this.item.knok.createDate.getTime() + (this.item.knok.duration * oneDayTiks));
      let v: number = this.truncateToInt((endDate.getTime() - currDate.getTime()) * 24 / oneDayTiks);
      if (v > 24) {
        this.timeLeft = `${this.truncateToInt(v / 24)} days`;
      } else if ( v === 1) {
        this.timeLeft = `${v} hour`;
      } else {
        this.timeLeft = `${v} hours`;
      }

      const entryPriceCenter: number = this.item.knok.entryPriceFrom + (this.item.knok.entryPriceTo - this.item.knok.entryPriceFrom) / 2;
      const exitPriceCenter: number = this.item.knok.exitPriceFrom + (this.item.knok.exitPriceTo - this.item.knok.exitPriceFrom) / 2;

      console.log(`${this.item.knok.exitPriceFrom} - ${exitPriceCenter} - ${this.item.knok.exitPriceTo}`);
      for (let i: number = 0; i < this.item.chartData.length; i++) {
        // let date: Date = this.item.chartData[i].x; // new Date(this.item.knok.createDate.getTime() + res );
        // let nextDate: Date = i < (this.item.chartData.length - 1) ? this.item.chartData[i + 1].x : null;

        // if (currDate.getDate() === date.getDate() &&
        //   currDate.getMonth() === date.getMonth() &&
        //   currDate.getFullYear() === date.getFullYear() &&
        //   nextDate && date.getDate() !== nextDate.getDate()) {

        //   pointBackgroundColorData.push('rgba(0, 128, 0, 0.9)');
        //   pointBorderColorData.push('rgba(255, 255, 255, 1)');
        //   currDate = date;
        // } else {
        //   if (currDate.getTime() > date.getTime()) {
        //     pointBackgroundColorData.push('rgba(0,0,0,0)');
        //     pointBorderColorData.push('rgba(0,0,0,0)');
        //   } else {
        //     if (endDate.getTime() === date.getTime()) {
        //       pointBackgroundColorData.push('rgba(0,0,0,0)');
        //       pointBorderColorData.push('rgba(0,0,0,0)');
        //     }
        //   }
        // }
        if ( i === this.item.chartData.length - 1) {
          pointBackgroundColorData.push('rgba(0, 128, 0, 0.9)');
          pointBorderColorData.push('rgba(255, 255, 255, 1)');
        } else {
          pointBackgroundColorData.push('rgba(0,0,0,0)');
          pointBorderColorData.push('rgba(0,0,0,0)');
        }
      }

      const currentRate: Date =  this.item.chartData.length > 0 ? this.item.chartData[this.item.chartData.length - 1].x : currDate;
      this.item.chartData.push({x: endDate, y: null});

      if (this.canvas && this.canvas.nativeElement) {
        const self: ExOngoingItemComponent = this;
        setTimeout(() => {
          this.chart = new Chart(this.canvas.nativeElement, {
          type: 'line',
          data: {
              datasets: [
              {
                  pointBackgroundColor: pointBackgroundColorData, // ['rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0, 128, 0, 0.9)'],
                  pointBorderColor: pointBorderColorData, // ['rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(0,0,0,0)', 'rgba(255, 255, 255, 1)'],
                  backgroundColor: 'rgba(0,0,0,0.1)',
                  borderWidth: 2,
                  hoverBackgroundColor: 'rgba(0,0,0,0)',
                  hoverBorderColor: 'rgba(0,0,0,0)',
                  yAxisID: 'A',
                  data: this.item.chartData,
                  borderColor: 'rgba(0,0,0,0.4)',
                  fill: false
              }
            ]
          },
          options: {
            maintainAspectRatio: false,
            elements: {
                point: {
                    radius: 8,
                    hitRadius: 8,
                    hoverRadius: 8
                }
                // line: {
                //     tension: 0 // disables bezier curves
                // }
            },
            scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                },
                    type: 'time',
                    time: {
                        unit: 'month',
                        displayFormats: {
                            day: 'MMM yyyy'
                        }
                    },
                    ticks: {
                        display: false,
                        beginAtZero: false,
                        // stepSize: currDate.getTime() / 10,
                        min: this.item.knok.createDate,
                        max: endDate
                    }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                },
                  id: 'A',
                    type: 'linear',
                    position: 'left',
                    ticks: {
                        display: true,
                        beginAtZero: false,
                        stepSize: entryPriceCenter,
                        min: self.item.knok.stopLoss,
                        max: self.item.knok.exitPriceTo,
                        fontColor: ['rgba(44,44,44,0.8)', 'rgba(44,44,44,0.8)', 'rgba(0,0,0,1)'],
                        callback: (value: number, index: number, values: string): string => {
                          if ((Math.round(value * 100) / 100) === (Math.round(entryPriceCenter * 100) / 100)) {
                          // if (value >= self.item.knok.entryPriceFrom && value <= self.item.knok.entryPriceTo) {
                              return `${Math.round(self.item.knok.entryPriceFrom * 100) / 100}~${Math.round(self.item.knok.entryPriceTo * 100) / 100}`;
                          }
                          return '';
                        }
                    }
                },
                {
                  gridLines: {
                    display: false
                },
                  id: 'B',
                  type: 'linear',
                  position: 'right',
                  ticks: {
                      display: true,
                      beginAtZero: false,
                      stepSize: exitPriceCenter,
                      min: self.item.knok.stopLoss,
                      max: self.item.knok.exitPriceTo,
                      fontColor: ['rgba(255,0,0,0.5)', 'rgba(0,128,0, 0.5)', 'rgba(255,0,0,0.5)'],
                      callback: (value: number, index: number, values: string): string => {
                          if (value ===  self.item.knok.stopLoss) {
                            return value.toFixed(2);
                          }
                          if ((Math.round(value * 100) / 100) === (Math.round(exitPriceCenter * 100) / 100)) {
                          // if (value >= self.item.knok.exitPriceFrom && value < self.item.knok.exitPriceTo) {
                              return `${Math.round(self.item.knok.exitPriceFrom * 100) / 100}~${Math.round(self.item.knok.exitPriceTo * 100) / 100}`;
                          }
                          return '';
                      }
                  }
              }]
            },
            annotation: {
              drawTime: 'beforeDatasetsDraw',
                    annotations: [{
                    type: 'line',
                    mode: 'horizontal',
                    scaleID: 'A', // this is the default value. if your chart has custom IDs for the axis you need to use that value here
                    value: this.item.knok.stopLoss, // should be a number
                    borderColor: 'red',
                    borderWidth: 3
                    },
                    {
                      type: 'line',
                      mode: 'horizontal',
                      scaleID: 'A', // this is the default value. if your chart has custom IDs for the axis you need to use that value here
                      value: entryPriceCenter, // should be a number
                      borderColor: 'black',
                      borderWidth: 1,
                      borderDash: [10, 4]
                    },
                    {
                      type: 'line',
                      mode: 'horizontal',
                      scaleID: 'A', // this is the default value. if your chart has custom IDs for the axis you need to use that value here
                      value: exitPriceCenter, // should be a number
                      borderColor: 'rgb(0,128,0)',
                      borderWidth: 2
                    },
                  {
                      type: 'box',
                      xScaleID: 'x-axis-0',
                      yScaleID: 'A',
                      xMin: currentRate, // currDate,
                      xMax: endDate,
                      yMin: this.item.knok.stopLoss,
                      yMax: this.item.knok.exitPriceTo,
                      backgroundColor: 'rgba(0, 0, 0, 0.1)',
                      borderColor: 'rgba(0, 0, 0, 0)',
                      borderWidth: 1
                  },
                  {
                    type: 'box',
                    xScaleID: 'x-axis-0',
                    yScaleID: 'A',
                    xMin: this.item.knok.createDate,
                    xMax: endDate,
                    yMin: this.item.knok.entryPriceFrom,
                    yMax: this.item.knok.entryPriceTo,
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                    borderColor: 'rgba(128, 0, 0, 0)',
                    borderWidth: 1
                  },
                  {
                    type: 'box',
                    xScaleID: 'x-axis-0',
                    yScaleID: 'A',
                    xMin: this.item.knok.createDate,
                    xMax: endDate,
                    yMin: this.item.knok.exitPriceFrom,
                    yMax: this.item.knok.exitPriceTo,
                    backgroundColor: 'rgba(0, 128, 0, 0.288)',
                    borderColor: 'rgba(0, 0, 128, 0)',
                    borderWidth: 1
                }]
            },
            legend: {
                display: false
            },
            title: {
                display: false
            },
            tooltips: {
                enabled: false
            }
          }
          });
        }, 10);
      }
    }

    ngOnInit(): void {
      this.initChart();
    }

    get avatarHref(): string {
      return `${SETTINGS.API_URL}` + this.item.knokser.href;
    }

    get percentShiftCaption(): number {
      return 50 + 290; // * (this.daysLeft / this.item.knok.duration);
    }

    private addPadding(val: number): string {
      let res: string = val.toString();
      while (res.length < 2) {
        res = '0' + res;
      }
      return res;
    }

    private floorFigure(figure: number, decimals: number): number {
      if (!decimals) {
        decimals = 0;
      }
      let d: number = Math.pow(10, decimals);
      d = (parseInt((figure * d).toString(), null) / d);
      return parseInt(d.toFixed(decimals), null);
    }

    private truncateToInt(n: number): number {
        return parseInt(n.toString().match(/^-?\d+(?:\.\d{0})?/)[0], 10);
    }
}
