import { AfterViewChecked, AfterViewInit, Component, Directive, ElementRef, EventEmitter, Inject, Input, OnDestroy, OnInit, Output, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Router, UrlTree } from '@angular/router';

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, IFeedKnok, IFeedUser, IKnokFeedData, IKnokserProfile, KnokService, UserService } from '../../shared';
import { getKnokserRank, convertUTCDateToLocalDate } from '../../shared/helpers';

import { Chart } from 'chart.js';
import * as MDC from 'material-components-web';
import { TranslateService } from '@ngx-translate/core';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'knk-discovery-item',
  styleUrls: ['./discoveryitem.component.scss'],
  templateUrl: './discoveryitem.component.pug'
})
export class DiscoveryItemComponent implements AfterViewInit, OnInit, OnDestroy {
  @Input('isbutton') isbutton: boolean;
  @Input('isUser') isUser: boolean = false;
  @Input('currentUserId') currentUserId: number;
  @Input('item') item: IKnokFeedData;
  @Output() changedItem: EventEmitter<void> = new EventEmitter<void>();

  lang: string = null;
  observer: MutationObserver;
  showProgress: boolean = true;

  maxVal: number = 24;
  minVal: number = 0;

  startHeight: number;
  isCollapsed: boolean = true;
  expandChart: boolean = false;
  minutesLeft?: number = null;
  timeStamp: Date = null;

  public _selectedItems: Array<{ label: string, value: string }> = [];
  public watchedItems: Array<{ label: string, value: string }>;
  private _items: Array<{ label: string, value: string }>;
  private dialogAfterClosedSubscription: Subscription;
  private _saved: boolean = false;
  private ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(public dialog: MatDialog,
              protected element: ElementRef,
              private viewContainerRef: ViewContainerRef,
              private router: Router,
              private route: ActivatedRoute,
              private translateService: TranslateService,
              private knokService: KnokService,
              private userService: UserService) {
    this._items = [];
  }

  showProfile(): void {
    this.knokService.knokserProfile(this.item.knoker.userId).subscribe(profile => {
      // let item: IKnokFeedData = this.item;
      let dialogRef: MatDialogRef<KnokserProfileDialogComponent, IKnokserProfile> = this.dialog.open(KnokserProfileDialogComponent, {
        viewContainerRef: this.viewContainerRef,
        panelClass: 'knk-overlay-pane',
        backdropClass: 'knk-overlay-backdrop',
        width: '860px',
        disableClose: false,
        autoFocus: false,
        data: Object.assign({currentUserId: this.currentUserId},  profile)
      });

      this.dialogAfterClosedSubscription = dialogRef.afterClosed().subscribe(result => {
        console.log('The dialog was closed');
        if (result) {
          this.changedItem.emit();
        }
      });
    });

    if (this.dialogAfterClosedSubscription) {
      this.dialogAfterClosedSubscription.unsubscribe();
    }
  }

  openKnok(data: IKnokFeedData): void {
    let knok: IFeedKnok = data.knok;
    let knokId: number = knok.knokId || -1;
    if (knokId > 0) {
      Observable.timer(1000).takeUntil(this.ngUnsubscribe).subscribe((): void => {
        this.ngUnsubscribe.next();
        let url: UrlTree = this.router.createUrlTree(['.', {outlets: {'knok': [knokId]}}], {relativeTo: this.route.parent});
        this.router.navigateByUrl(url);
      });
    }
  }

  buyKnok(knok: IKnokFeedData): void {
    let item: IKnokFeedData = Object.assign({timeLeft: this.timeLeft}, this.item);
    Observable.timer(1000).takeUntil(this.ngUnsubscribe).subscribe((): void => {
      this.ngUnsubscribe.next();

      if (this.dialogAfterClosedSubscription) {
        this.dialogAfterClosedSubscription.unsubscribe();
      }

      let dialogRef: MatDialogRef<BuyKnokDialogComponent, IKnokFeedData> = this.dialog.open(BuyKnokDialogComponent, {
        viewContainerRef: this.viewContainerRef,
        panelClass: 'knk-overlay-pane',
        backdropClass: 'knk-overlay-backdrop',
        width: '400px',
        disableClose: false,
        autoFocus: false,
        data: item
      });

      this.dialogAfterClosedSubscription = dialogRef.afterClosed().debounceTime(10).subscribe(result => {
        console.warn('The knok was bought');
        if (result) {
          this.changedItem.emit();
        }
      });
    });
  }

  buttonOverCaption(): void {
    this.showProgress = false;
  }

  buttonLeaveCaption(): void {
    this.showProgress = true;
  }

  createItems(): void {
    this._items.length = 0;
    if (this.item && this.item.knok) {
      this.minutesLeft = this.item.knok.minutesLeftOnFeed;
      this.timeStamp = new Date();
    }
    // let max: number = 20;
    // let min: number = 10;
    // let numItems: number = Math.floor(Math.random() * (max - min + 1)) + min;
    // console.log("Adding " + numItems.toString() + " items");
    // max = 6;
    // min = 3;
    // let i: number;
    // for (i = 0; i < numItems; i++) {
    //   let numWords: number = Math.floor(Math.random() * (max - min + 1)) + min;
    //   // let label: string = this._lipsum.generate(numWords);
    //   this._items.push({ label: 'test', value: i.toString()});
    //   //  console.log(label);
    // }
  }

  ngOnInit(): void {
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;
    this.createItems();
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();

    if (this.dialogAfterClosedSubscription) {
      this.dialogAfterClosedSubscription.unsubscribe();
    }
  }

  ngAfterViewInit(): void {
    // todo: create auto init directive and clean it
    MDC.autoInit(this.element.nativeElement);
    // let htmlRef: AbstractControl = this.elementRef.nativeElement.querySelector(`#canvas`);
  }

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

  get progressValue(): number {
    const date: Date = new Date();
    const timeDiff: number = Math.abs(date.getTime() - new Date(this.item.knok.publishedDate).getTime());
    const diffMinutes: number = (24 * 60) - Math.ceil(timeDiff / (1000 * 60));
    // var diffHours = Math.ceil(timeDiff / (1000 * 3600));
    date.setMinutes(diffMinutes);
    return (diffMinutes / 14.4);
  }

  get timeLeft(): string[] {
    if (this.minutesLeft && this.timeStamp) {
      const date: Date = new Date();
      // const timeDiff: number = Math.abs(date.getTime() - new Date(this.item.knok.createDate).getTime());
      // const minutesLeft: number = (24 * 60) - Math.ceil(timeDiff / (1000 * 60));
      const timeDiff: number = Math.abs(date.getTime() - this.timeStamp.getTime());
      const totalMinutesLeft: number = this.minutesLeft - Math.ceil(timeDiff / (1000 * 60));
      let hrs: number = this.floorFigure(totalMinutesLeft / 60, 0);
      const mins: number = totalMinutesLeft - hrs * 60;
      const days: number = this.floorFigure(hrs / 24, 0);
      hrs = hrs - days * 24;
      if (totalMinutesLeft > 0) {
        return [this.addPadding(days), this.addPadding(hrs), this.addPadding((mins))];
      }
    }
    return ['00', '00', '00'];
  }

  get ratingValue(): Array<number> {
    const arraycount: number = 5;
    let array: Array<number> = [0, 0, 0, 0, 0];
    array.forEach((el, i) => {
      if (i <= this.item.knoker.knokerRatingPoints - 1) {
        array[i] = 1;
      } else if (this.item.knoker.knokerRatingPoints % 1 > 0) {
        array[i] = 0.5;
      } else {
        array[i] = 0;
      }
    });
    return array;
  }

  get isMine(): boolean {
    return this.item.knoker.userId === this.currentUserId;
  }

  get rankValue(): string {
    return getKnokserRank(this.item.knoker.knokserRank);
  }

  get profitValue(): string {
    // Low: up to 30% potential profit.
    // Medium: 30 -100% potential profit.
    // High: More than 100% potential profit.
    // if (this.item.knok.potentialProfit <= 0.3) {
    //   return 'Low';
    // } else if (this.item.knok.potentialProfit > 0.3 && this.item.knok.potentialProfit <= 1) {
    //   return 'Med.';
    // } else {
    //   return 'High';
    // }
    return this.item.knok.potentialProfit === 1 ? 'Low' :
      this.item.knok.potentialProfit === 2 ? 'Med.' :
        this.item.knok.potentialProfit === 3 ? 'High' :
        this.item.knok.potentialProfit === 4 ? 'Very High' : 'Unkn.';
  }

  get saved(): boolean {
    return this._saved;
  }

  set saved(value: boolean) {
    this._saved = Boolean(value);
  }

  objectToString(object: any): string {
    return JSON.stringify(object);
  }

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

@Component({
  selector: 'knk-knokser-profile-dialog',
  styleUrls: ['knokser.profile.dialog.scss'],
  templateUrl: 'knokser.profile.dialog.html'
})
export class KnokserProfileDialogComponent implements OnInit, AfterViewInit {
  isFollowed: boolean = false;
  isDirty: boolean = false;
  userFollowers: number;
  activityTabIndex: number;
  chart: Chart;
  @ViewChild('canvas') canvas;

  constructor(public dialogRef: MatDialogRef<KnokserProfileDialogComponent>,
              @Inject(MAT_DIALOG_DATA) private data: IKnokserProfile,
              protected element: ElementRef,
              private accountService: AccountService) {
  }

  ngOnInit(): void {
    this.userFollowers = this.data.userFollowers;
    this.accountService.isFollowed(this.data.userId).subscribe((res) => {
      this.isFollowed = res;
    });
    this.activityTabIndex = 0;
  }

  ngAfterViewInit(): void {
    this.initChart();
    // todo: create auto init directive and clean it
    MDC.autoInit(this.element.nativeElement);
  }

  log(...args: any[]): void {
    console.log(args);
  }

  initChart(): void {
    if (this.canvas && this.canvas.nativeElement) {
      setTimeout(() => {
        const ctx: CanvasRenderingContext2D = this.canvas.nativeElement.getContext('2d');
        this.chart = new Chart(this.canvas.nativeElement, {
          type: 'line',
          data: {
            datasets: [
              {
                showLine: true,
                fill: true,
                backgroundColor: this.getCanvasLinearGradient(ctx, [[0, 'rgba(127, 128, 255, 0.25)'], [1, 'rgba(255, 255, 255, 0.25)']]),
                borderColor: 'rgba(127, 128, 255, 1)',
                borderWidth: 2,
                pointBackgroundColor: 'rgba(127, 128, 255, 1)',
                pointBorderColor: 'rgba(255, 255, 255, 1)',
                pointBorderWidth: 2,
                pointRadius: [0, 0, 0, 0, 0, 0, 0, 6],
                data: [
                  {x: new Date('11/11/2017 23:15:30'), y: 90},
                  {x: new Date('11/28/2017 13:15:30'), y: 40},
                  {x: new Date('12/03/2017 23:15:30'), y: 20},
                  {x: new Date('12/23/2017 23:15:30'), y: 60},
                  {x: new Date('01/04/2018 03:15:30'), y: 40},
                  {x: new Date('01/24/2018 13:15:30'), y: 50},
                  {x: new Date('02/05/2018 00:00:00'), y: 70},
                  {x: new Date('03/12/2018 00:00:00'), y: 90}
                ],
                yAxisID: 'A'
              },
              {
                showLine: true,
                fill: true,
                backgroundColor: this.getCanvasLinearGradient(ctx, [[0, 'rgba(0, 186, 255, 0.25)'], [1, 'rgba(255, 255, 255, 0.25)']]),
                borderColor: 'rgba(0, 186, 255, 1)',
                borderWidth: 2,
                pointBackgroundColor: 'rgba(0, 186, 255, 1)',
                pointBorderColor: 'rgba(255, 255, 255, 1)',
                pointBorderWidth: 2,
                pointRadius: [0, 0, 0, 0, 0, 0, 0, 6],
                data: [
                  {x: new Date('11/11/2017 23:15:30'), y: 20},
                  {x: new Date('11/28/2017 13:15:30'), y: 60},
                  {x: new Date('12/03/2017 23:15:30'), y: 50},
                  {x: new Date('12/23/2017 23:15:30'), y: 30},
                  {x: new Date('01/04/2018 03:15:30'), y: 70},
                  {x: new Date('01/24/2018 13:15:30'), y: 90},
                  {x: new Date('02/05/2018 00:00:00'), y: 50},
                  {x: new Date('03/12/2018 00:00:00'), y: 10}
                ],
                yAxisID: 'B'
              }
            ]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            easing: 'easeInOutBack',
            elements: {
              line: {
                tension: 0.5
              }
            },
            scales: {
              xAxes: [{
                display: false,
                gridLines: {
                  display: false,
                  drawBorder: false
                },
                id: 'D',
                type: 'time',
                time: {
                  unit: 'minute',
                  displayFormats: {
                    day: 'MMM yyyy'
                  }
                },
                ticks: {
                  display: false,
                  beginAtZero: false,
                  min: (new Date('11/01/2017')),
                  max: (new Date('04/11/2018'))
                }
              }],
              yAxes: [{
                ticks: {
                  min: 0,
                  max: 100,
                  beginAtZero: true,
                  maxTicksLimit: 5
                },
                gridLines: {
                  drawTicks: true,
                  display: true
                }
              }, {
                id: 'A',
                type: 'linear',
                position: 'left',
                display: true,
                ticks: {
                  display: false,
                  min: 0,
                  max: 100,
                  beginAtZero: true,
                  maxTicksLimit: 5
                },
                gridLines: {
                  display: false,
                  drawBorder: false
                }
              },
                {
                  id: 'B',
                  type: 'linear',
                  position: 'right',
                  display: true,
                  ticks: {
                    display: false,
                    min: 0,
                    max: 100,
                    beginAtZero: true,
                    maxTicksLimit: 5
                  },
                  gridLines: {
                    display: false,
                    drawBorder: false
                  }
                }]
            },
            legend: {
              display: false
            },
            title: {
              display: false
            },
            tooltips: {
              enabled: false
            }
          }
        });

        /*this.chart = new Chart(this.canvas.nativeElement, {
          type: 'line',
          data: {
            datasets: [
              {
                pointBackgroundColor: ['rgba(0, 186, 255, 0.9)'], // ['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)', '#FF9900'],
                pointBorderColor: ['rgba(255, 255, 255, 1)'], // ['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)', '#FF9900'],
                backgroundColor: 'rgba(0, 186, 255,0.1)',
                borderWidth: 2,
                hoverBackgroundColor: 'rgba(0, 0, 0, 0)',
                hoverBorderColor: 'rgba(0, 0, 0, 0)',
                yAxisID: 'A',
                data: [
                  {x: new Date('11/11/2017 23:15:30'), y: 20},
                  {x: new Date('11/28/2017 13:15:30'), y: 50},
                  {x: new Date('12/03/2017 23:15:30'), y: 45},
                  {x: new Date('12/23/2017 23:15:30'), y: 70},
                  {x: new Date('01/04/2018 03:15:30'), y: 50},
                  {x: new Date('01/24/2018 13:15:30'), y: 60},
                  {x: new Date('02/05/2018 00:00:00'), y: 30},
                  {x: new Date('03/12/2018 00:00:00'), y: 72}
                ],
                borderColor: 'rgba(0, 186, 255 ,0.4)',
                fill: true
              },
              {
                pointBackgroundColor: ['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)', '#6699FF'],
                pointBorderColor: ['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)', '#6699FF'],
                backgroundColor: 'rgba(0,0,0,0.1)',
                borderWidth: 2,
                hoverBackgroundColor: 'rgba(0,0,0,0)',
                hoverBorderColor: 'rgba(0,0,0,0)',
                yAxisID: 'B',
                data: [
                  {x: new Date('11/11/2017 23:15:30'), y: 0.01},
                  {x: new Date('11/28/2017 13:15:30'), y: 0.005},
                  {x: new Date('12/03/2017 23:15:30'), y: 0.015},
                  {x: new Date('12/23/2017 23:15:30'), y: 0.01},
                  {x: new Date('01/04/2018 03:15:30'), y: 0.015},
                  {x: new Date('01/24/2018 13:15:30'), y: 0.02},
                  {x: new Date('02/05/2018 00:00:00'), y: 0.015},
                  {x: new Date('03/12/2018 00:00:00'), y: 0.017}
                ],
                borderColor: '#6699FF',
                fill: true
              }
            ]
          },
          options: {
            maintainAspectRatio: false,
            elements: {
              point: {
                radius: 5,
                hitRadius: 5,
                hoverRadius: 5
              },
              line: {
                tension: 0 // disables bezier curves
              }
            },
            scales: {
              xAxes: [{
                type: 'time',
                time: {
                  unit: 'month',
                  displayFormats: {
                    day: 'MMM yyyy'
                  }
                },
                ticks: {
                  display: true,
                  beginAtZero: false,
                  stepSize: 0.5,
                  min: (new Date('11/01/2017')),
                  max: (new Date('04/11/2018')) // .getTime() + this.newknok.duration * 1000 * 60 * 60 * 24)
                }
              }],
              yAxes: [{
                id: 'A',
                type: 'linear',
                position: 'left',
                ticks: {
                  display: true,
                  beginAtZero: false,
                  stepSize: 20,
                  min: 0,
                  max: 100,
                  fontColor: ['#FF9900', '#FF9900', '#FF9900', '#FF9900', '#FF9900', '#FF9900']
                  // callback: (value: number, index: number, values: string): string => {
                  //     if (value === self.newknok.stopLoss) {
                  //         return 'Stop Loss ' + value.toFixed(2);
                  //     }
                  //     if (value === self.newknok.entryPriceFrom) {
                  //         return 'Entry ' + value.toFixed(2);
                  //     }

                  //     if (value === self.newknok.exitPriceTo) {
                  //         return 'Exit ' + value.toFixed(2);
                  //     }
                  //     return value.toFixed(2);
                  // }
                }
              },
                {
                  id: 'B',
                  type: 'linear',
                  position: 'right',
                  ticks: {
                    display: true,
                    beginAtZero: false,
                    stepSize: 0.005,
                    min: 0,
                    max: 0.025,
                    fontColor: ['#6699FF', '#6699FF', '#6699FF', '#6699FF', '#6699FF', '#6699FF']
                  }
                }]
            },
            legend: {
              display: false
            },
            title: {
              display: false
            },
            tooltips: {
              enabled: false
            }
          }
        });*/
      }, 500);
    }
  }

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

  get ratingValue(): Array<number> {
    const arraycount: number = 5;
    let array: Array<number> = [0, 0, 0, 0, 0];
    array.forEach((el, i) => {
      if (i <= this.data.knokerRatingPoints - 1) {
        array[i] = 1;
      } else if (this.data.knokerRatingPoints % 1 > 0) {
        array[i] = 0.5;
      } else {
        array[i] = 0;
      }
    });
    return array;
  }

  get rankValue(): string {
    return getKnokserRank(this.data.knokserRank);
  }

  get activeFor(): string {
    if (this.data.registrationDate) {
      return this.timeBetween(convertUTCDateToLocalDate(new Date(this.data.registrationDate)), new Date());
    }
    return '';
  }

  get boughtBy(): string {
    if (this.data.boughtBy) {
      return this.data.boughtBy >= 1000 ? `${Math.round(this.data.boughtBy / 1000)}K` : `${Math.round(this.data.boughtBy * 100) / 100}`;
    }
    return '';
  }

  get publishedKnoks(): number {
    if (this.data.publishedKnoks) {
      return this.data.publishedKnoks;
    }
    return 0;
  }

  get successSequence(): number {
    if (this.data.successSequence) {
      return this.data.successSequence;
    }
    return 0;
  }

  get distanceFromTarget(): number {
    if (this.data.distanceFromTarget) {
      return this.data.distanceFromTarget;
    }
    return 0;
  }

  get successRate(): number {
    if (this.data.successRate) {
      return this.data.successRate;
    }
    return 0;
  }

  close(): void {
    this.dialogRef.close(this.isDirty);
  }

  followUser(knoker: IKnokserProfile): void {
    this.accountService.addFollow(knoker.userId).subscribe((res) => {
      console.log('addFollow UserId: ' + res.toString());
      this.userFollowers = res.items.length;
      this.isFollowed = (res.items && res.items.find(i => i === knoker.userId) === knoker.userId);
      this.isDirty = true;
    });
  }

  unfollowUser(knoker: IKnokserProfile): void {
    this.accountService.removeFollow(knoker.userId).subscribe((res) => {
      console.log('removeFollow UserId: ' + res.toString());
      this.userFollowers = res.items.length;
      this.isFollowed = (res.items && res.items.find(i => i === knoker.userId) !== undefined);
      this.isDirty = true;
    });
  }

  private getCanvasLinearGradient(ctx: CanvasRenderingContext2D, colors: [number, string][]): CanvasGradient {
    const gradient: CanvasGradient = ctx.createLinearGradient(0, 0, 0, 100);
    colors.forEach((value: [number, string]): void => {
      const index: number = value[0];
      const color: string = value[1];
      gradient.addColorStop(index, color);
    });
    return gradient;
  }

  private timeBetween( date1: Date, date2: Date ): string {
    // Get 1 day in milliseconds
    const one_day: number = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    let date1_ms: number = date1.getTime();
    let date2_ms: number = date2.getTime();

    // Calculate the difference in milliseconds
    let difference_ms: number = date2_ms - date1_ms;
    // take out milliseconds
    difference_ms = difference_ms / 1000;
    // let seconds: number = Math.floor(difference_ms % 60);
    difference_ms = difference_ms / 60;
    // let minutes: number = Math.floor(difference_ms % 60);
    difference_ms = difference_ms / 60;
    // let hours: number = Math.floor(difference_ms % 24);
    let days: number = Math.floor(difference_ms / 24);

    // let years: number = date2.getFullYear() - date1.getFullYear();
    // let months: number = date2.getMonth() - date1.getMonth() + (years * 12);
    let val: number;
    // X > 364 => +(X % 365) years
    // if (days > 364) {
      val = Math.floor(days / 365);
      if ( val > 0) {
        return val === 1 ? `+1 year` : `+${val} years`;
      }
    // }
    // X = 30-364 days => +(X % 30) months
    // if (days <= 364 && days >= 30) {
      val = Math.floor(days / 30);
      if ( val > 0) {
        return val === 1 ? `+1 month` : `+${val} months`;
      }
    // }
    // X = 7-29 days => +(X % 7) weeks
    // if (days <= 29 && days >= 7) {
      val = Math.floor(days / 7);
      if ( val > 0) {
        return val === 1 ? `+1 week` : `+${val} weeks`;
      }
    // }
    // X = 0-6 days => +X days
    // if (days <= 0 && days >= 6) {
      return days === 1 ? `+1 day` : `+${days} days`;
    // }
  }
}

@Component({
  selector: 'knk-buy-knok-dialog',
  styleUrls: ['buy.knok.dialog.scss'],
  templateUrl: 'buy.knok.dialog.html'
})
export class BuyKnokDialogComponent implements OnInit, OnDestroy {
  lang: string;

  private dialogAfterOpenSubscription: Subscription;
  private purchaseKnokSubscription: Subscription;

  constructor(public dialogRef: MatDialogRef<BuyKnokDialogComponent>,
              @Inject(MAT_DIALOG_DATA) private data: IKnokFeedData,
              protected element: ElementRef,
              private router: Router,
              private route: ActivatedRoute,
              private translateService: TranslateService,
              private knokService: KnokService,
              private userService: UserService) {
  }

  ngOnInit(): void {
    this.lang = this.translateService.currentLang || this.translateService.defaultLang;
    this.dialogAfterOpenSubscription = this.dialogRef.afterOpen().subscribe(() => {
      const timeout: any = setTimeout((): void => {
        // todo: create auto init directive and clean it
        MDC.autoInit(this.element.nativeElement);
        clearInterval(timeout);
      }, 10);
    });
  }

  ngOnDestroy(): void {
    if (this.dialogAfterOpenSubscription) {
      this.dialogAfterOpenSubscription.unsubscribe();
    }

    if (this.purchaseKnokSubscription) {
      this.purchaseKnokSubscription.unsubscribe();
    }
  }

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

  get timeLeft(): string[] {
    if (this.data['timeLeft']) {
      return this.data['timeLeft'];
    }
    return ['00', '00', '00'];
  }

  close(): void {
    this.dialogRef.close(false);
  }

  purchaseKnok(knok: IFeedKnok): void {
    if (this.purchaseKnokSubscription) {
      this.purchaseKnokSubscription.unsubscribe();
    }

    this.purchaseKnokSubscription = this.knokService.purchaseKnok(knok.knokId).subscribe((res) => {
      console.log(res);
      if (res.value) {
        this.dialogRef.close(true);
        let url: UrlTree = this.router.createUrlTree(['.', {outlets: {'knok': [knok.knokId]}}], {relativeTo: this.route.parent});
        this.router.navigateByUrl(url);

        // todo: refresh user and tokens
        this.userService.loadUser()
          .take(1)
          .subscribe(() => undefined);
      }
    });
  }

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