import { AfterViewInit, Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild, NgZone, ViewContainerRef, ViewRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IKnokFeedArgs, IKnokFeedData, IKnokFeedDataList, KnokRollService, LoaderService, TokenService } from '../core/shared';
import { FilterService, KnokService, UserService } from '../core/shared';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs/Subscription';
import { ILog, Log, applyMixins, ViewRefWatcherService } from '../core/shared/helpers';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'knk-discover',
  styleUrls: ['./discover.component.scss'],
  templateUrl: './discover.component.html'
})
export class DiscoverComponent implements OnInit, OnDestroy, ILog {
  @ViewChild('filter', {read: ViewContainerRef}) filterRef: ViewContainerRef;
  @ViewChild('sort', {read: ViewContainerRef}) sortRef: ViewContainerRef;

  loaded: boolean = false;
  lang: string;
  showScroll: boolean = false;
  items: Array<IKnokFeedData>;
  currentUserId: number;

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

  private loaderSubscription: Subscription;
  private filterSubscription: Subscription;
  private discoverKnoksSubscription: Subscription;

  constructor(private translateService: TranslateService,
              private tokenService: TokenService,
              private route: ActivatedRoute,
              private ngZone: NgZone,
              private loaderService: LoaderService,
              private userService: UserService,
              private knokService: KnokService,
              private filterService: FilterService,
              private viewWatcher: ViewRefWatcherService,
              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(u => {
        this.currentUserId = u.user.userId;
      });
    }

    if (this.filterService) {
      this.filterService.filterType = 'discover';
      this.filterSubscription = this.filterService.feedArgsObservable.subscribe((args: IKnokFeedArgs | null) => {
        this.discoverKnoksSubscription = this.knokService.getDiscoverKnoks(args).subscribe((listItems: IKnokFeedDataList): void => {
          if (listItems) {
            /*if (listItems.items.length >= 1) {
              listItems.items[0].knok.entryPriceTouched = true;
            }*/
            this.items = listItems.items;
          } else {
            this.items = [];
          }

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

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

      const args: IKnokFeedArgs = {
        sortOrderAsc: false,
        sortField: 1,
        raitings: null,
        knoksersIFollow: false,
        containsTA: false,
        containsFA: false,
        knokPriceMax: null,
        knokPriceMin: null,
        exchangesIds: null,
        tradingPairs: null
      };
      this.filterService.feedArgs = args;
    }

    /*if (this.ngZone && this.loaderService) {
      this.ngZone.runOutsideAngular(() => {
        this.loaderSubscription = this.loaderService.subscribeLoader(this);
      });
    }*/
  }

  ngOnDestroy(): void {
    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(DiscoverComponent, [Log]);
