import { Location } from '@angular/common';
import { Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Directive, Input, NgModule } from '@angular/core';
import { FormControl, FormGroup, FormsModule, NgForm, Validators } from '@angular/forms';
// import { UniqueSelectionDispatcher } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';

import { IApiError, IDiscoverKnoks, IFilter, IKnokFeedArgs, IKnokFeedData, IKnokFeedDataList, TokenService } from '../core/shared';
import { ICountry } from '../core/shared/country/country.model';
import { CountryService } from '../core/shared/country/country.service';

import { ICurrency, IExchange, IUser, IUserCredentials, User } from '../core/shared';

import { CurrencyService, ExchangeService, FilterService, KnokService, LanguageService, UserService } from '../core/shared';

import { TranslateService } from '@ngx-translate/core';
import { ILanguage, ILanguages } from '../core/shared/language/language.model';

import { IDiscoverKnok } from '../core/shared';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'knk-discover',
  styleUrls: ['./discover.component.scss'],
  templateUrl: './discover.component.html'
})
export class DiscoverComponent implements OnInit, OnDestroy {
  lang: string;
  showScroll: boolean = false;
  ascSort: boolean = false;
  sortField: number = 1;

  knoksersIFollow: boolean = false;
  containsTA: boolean = false;
  containsFA: boolean = false;

  expandedExchanges: boolean = false;
  exchanges: IExchange[] = null;

  availableExcahnges: IExchange[];
  availableTradingPairs: ICurrency[];

  expandedTradingPairs: boolean = false;
  tradingPairs: ICurrency[];

  filter: IFilter;
  ratingRange: number = 3;
  priceRange: number[] = [1, 4];
  sideSlideConfig = {
    connect: true,
    // start: [0, 5],
    step: 1,
    // margin: 2,
    padding: [0, 1],
    range: {
      min: 0,
      max: 5
    },
    // pips: {
    //   mode: 'steps',
    //   stepped: true,
    //   density: 2,
    //   values: 100
    // },
    orientation: 'vertical'
  };
  sidePriceConfig = {
    connect: true,
    // start: [1, 4],
    step: 1,
    margin: 0,
    // padding: [0, 1],
    range: {
      min: 0,
      max: 5
    },
    // pips: {
    //   mode: 'steps',
    //   stepped: true,
    //   density: 2,
    //   values: 100
    // },
    orientation: 'horizontal'
  };

  items: Array<IKnokFeedData>;
  private filterSubscription: Subscription;

  constructor(private translateService: TranslateService,
              private tokenService: TokenService,
              private route: ActivatedRoute,
              private knokService: KnokService,
              private exchangeService: ExchangeService,
              private currencyService: CurrencyService,
              private filterService: FilterService) {
  }

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

    // this.exchangeService.Exchanges.subscribe((exchanges) => {
    //   this.availableExcahnges = exchanges.items;
    // });

    this.currencyService.getCurrencies(null).subscribe((currencies) => {
      this.availableTradingPairs = currencies.items;
    });

    this.filterService.filterSettings.subscribe((filter) => {
      this.filter = filter;
    });

    // todo
    this.filterSubscription = this.filterService.feedArgsObservable.subscribe((args: IKnokFeedArgs | null) => {
      this.knokService.getDiscoverKnoks(args).subscribe((listItems: IKnokFeedDataList) => {
        if (listItems) {
          // Test
          if (listItems.items.length > 1) {
            listItems.items[1].knok.entryPriceTouched = true;
          }
          //
          this.items = listItems.items;
        } else {
          this.items = [];
        }
      });
    });

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

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

  selectExchange(exchange: IExchange): void {
    if (this.exchanges && this.exchanges.indexOf(exchange) !== -1) {
      this.exchanges.splice(this.exchanges.indexOf(exchange), 1);
      if (this.exchanges.length === 0) {
        this.exchanges = null;
      }
    } else {
      if (!this.exchanges) {
        this.exchanges = [];
      }
      this.exchanges.push(exchange);
    }
  }

  selectTradingPair(tradingPair: ICurrency): void {
    if (this.tradingPairs && this.tradingPairs.indexOf(tradingPair) !== -1) {
      this.tradingPairs.splice(this.tradingPairs.indexOf(tradingPair), 1);
      if (this.tradingPairs.length === 0) {
        this.tradingPairs = null;
      }
    } else {
      if (!this.tradingPairs) {
        this.tradingPairs = [];
      }
      this.tradingPairs.push(tradingPair);
    }
  }

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

  changeSortOrder(): void {
    this.ascSort = !this.ascSort;
    this.applyFilter();
  }

  applyFilter(): void {
    // this.listReload();
  }

  refreshList(): void {
    // this.listReload();
  }

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

  private listReload(): void {
    const filter: IKnokFeedArgs = {
      sortOrderAsc: this.ascSort,
      sortField: this.sortField,
      raitings: this.ratingRange,
      knoksersIFollow: this.knoksersIFollow,
      containsTA: this.containsTA,
      containsFA: this.containsFA,
      knokPriceMax: null, // this.priceRange[1] === 0 || this.priceRange[1] === 5 ? null : this.priceRange[1] * 10,
      knokPriceMin: null, // this.priceRange[0] === 0 || this.priceRange[0] === 5 ? null : this.priceRange[0] * 10,
      exchangesIds: this.exchanges ? this.exchanges.map((exchange: IExchange): number => {
        return exchange.exchangeId;
      }) : null,
      tradingPairs: this.tradingPairs ? this.tradingPairs.map((pair: ICurrency): string => {
        return pair.code;
      }) : null
    };

    this.knokService.getDiscoverKnoks(filter)
      .subscribe((listItems: IKnokFeedDataList) => {
        if (listItems) {
          // Test
          if (listItems.items.length > 1) {
            listItems.items[1].knok.entryPriceTouched = true;
          }
          //
          this.items = listItems.items;
        } else {
          this.items = [];
        }
      });
  }
}
