import { AfterViewInit, Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild, NgZone, ViewRef, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IKnokOngoingArgs, IKnokOngoingData, IKnokOngoingDataList, KnokRollService, LoaderService, TokenService } from '../core/shared';
import { FilterService, KnokService, UserService } from '../core/shared';
import { Subscription } from 'rxjs/Subscription';
import { ILog, Log, applyMixins } from '../core/shared/helpers';
import { Observable } from 'rxjs/Observable';
import { IUserAccounts } from '../core/shared/user/user.model';

@Component({
  selector: 'knk-track-ended',
  styleUrls: ['./ended.component.scss'],
  templateUrl: './ended.component.pug'
})
export class EndedComponent implements OnInit, OnDestroy, ILog {
  loaded: boolean = false;
  lang: string;
  showScroll: boolean = false;
  items: Array<IKnokOngoingData>;
  val: number = 10;
  userIsKnokser: boolean = false;

  /* Mixins */
  public log: (...args: any[]) => void;

  private filterSubscription: Subscription;
  private discoverKnoksSubscription: Subscription;
  private listSubscription: Subscription;

  constructor(private route: ActivatedRoute,
              private userService: UserService,
              private knokService: KnokService,
              private filterService: FilterService,
              private knokRollService: KnokRollService) {
  }

  ngOnInit(): void {
    const langParamName: string = 'lang';
    this.lang = this.route.snapshot.data[langParamName];

    if (this.userService) {
      const isTestPropertyName: string = 'test';
      this.userService.testParam = this.route.snapshot.data[isTestPropertyName];
      /*this.userService.loadUser().subscribe(user => {
        this.userIsKnokser = user.user.userIsKnokser;
        if (this.filterService) {
          this.filterService.userIsKnokser = this.userIsKnokser;
        }
      });*/
    }

    if (this.filterService) {
      this.filterService.filterType = 'ended';
      this.filterSubscription = this.filterService.feedArgsObservable.subscribe((args: IKnokOngoingArgs | null) => {
        this.items = [];

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

        let observables: Observable<any>[] = [this.knokService.getEndedKnoks(args), this.userService.loadUser()];
        let fetch$: Observable<any> = Observable.combineLatest(...observables);
        // let timer$: Observable<number> = Observable.timer(10, 30000);
        // let poll$: Observable<any> = timer$.exhaustMap(() => fetch$);
        this.listSubscription = fetch$.subscribe((result: [IKnokOngoingDataList, IUserAccounts]) => {
          let listItems: IKnokOngoingDataList = result[0];
          let accounts: IUserAccounts = result[1];

          // todo: remove
          // this.userIsKnokser = accounts.user.userIsKnokser;
          this.userIsKnokser = Boolean(this.route.snapshot.data.userIsKnokser);
          this.filterService.userIsKnokser = this.userIsKnokser;

          if (listItems && Array.isArray(listItems.items)) {
            if (!this.items.length) {
              this.items = listItems.items;
            } else {
              listItems.items.forEach(upd => {
                let i: Array<IKnokOngoingData> = this.items.filter(e2 => e2.knok.knokId === upd.knok.knokId);
                if (i && i.length > 0) {
                  i[0].knok.currentPrice = upd.knok.currentPrice;
                  i[0].chartData = upd.chartData;
                }
              });
            }

            let currentProfitTotal: number = 0;
            let potentialProfitTotal: number = 0;
            if (Array.isArray(this.items)) {
              this.items.forEach((e) => {
                currentProfitTotal += e.knok.currentProfit * 100;
                potentialProfitTotal += e.knok.potentialProfit * 100;
              });
            }
            this.filterService.totals = {currentProfit: Math.round(currentProfitTotal * 100) / 100, potentialProfit: Math.round(potentialProfitTotal * 100) / 100, knoksCount: this.items.length};
          } else {
            this.items = [];
          }

          let list: number[] = this.items.map((item: IKnokOngoingData) => +item.knok.knokId);
          this.knokRollService.set(list);

          this.loaded = true;
          this.log(listItems);
        }, (error: any): void => {
          this.loaded = true;
          this.log(error);
        });
      });

      const args: IKnokOngoingArgs = {
        sortOrderAsc: false,
        sortField: 1,
        exchangesIds: null,
        tradingPairs: null,
        published: null,
        gaining: null,
        losing: null,
        knokser: null
      };
      this.filterService.feedArgs = args;
    }
  }

  getChart(i: IKnokOngoingData): Array<{x: Date, y: number}> {
    return i.chartData;
  }

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

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

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

    this.knokRollService.clean();
  }

  refresh(event: any): void {
    this.log(event);
    this.filterService.feedArgsRefresh = false;
  }

  scrollToTop(): void {
    window.scrollTo(0, 0);
  }

  @HostListener('window:scroll', ['$event'])
  onWindowScroll($event: Event): void {
    this.showScroll = window.scrollY > 100 || document.body.scrollTop > 100;
  }
}

applyMixins(EndedComponent, [Log]);
