import { ProductService } from '@nodeart/productservice';
import { ActivatedRoute, Params } from '@angular/router';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { Component, OnInit, NgZone, Input } from '@angular/core';

@Component({
  selector: 'app-products-general',
  templateUrl: './products-general.component.html',
  styleUrls: ['./products-general.component.scss']
})
export class ProductsGeneralComponent implements OnInit {

  categoryIds = [];
  categories = [];
  dataReady = false;
  zone: NgZone;
  allCategoryIds;
  currentPage = 1;
  totalPages = 1;
  @Input() itemsOnPage = 100;
  from = 0;
  currentPageStream = new Subject<number>();
  @Input() generalCategoryId;
  constructor(private router: Router,
              private route: ActivatedRoute,
              private productService: ProductService) { 
                this.zone = new NgZone({enableLongStackTrace: false});
              }

  ngOnInit() {
    this.route.params.forEach((params: Params) => {
      if(params['id']){
        this.generalCategoryId = params['id'];
      }
      this.getCategoryIds(this.generalCategoryId);
    });
    this.currentPageStream.subscribe(newPage => {
      this.from = (this.currentPage - 1) * this.itemsOnPage;
    });
  }

  getCategoryIds(generalCategoryId){
    this.productService.getCategories(generalCategoryId).on('value', data => {
      if(data.val()){
        console.log(data.val());
        let categories = data.val().map(category => {
          category['_source']['id'] = category['_id'];
          return category['_source'];
        });
        this.categories = categories;
        let categoryIds = categories.map(category => {
          return category['id'];
        }); 
        console.log(categoryIds);
        this.categoryIds = categoryIds;

        // get Total pages of pagination
        this.getTotalPages(this.categoryIds);

        this.allCategoryIds = categoryIds;
        if(this.categoryIds.length > 0 && this.categories.length > 0){
          this.zone.run(() => this.dataReady = true);
        }
        console.log(this.dataReady);
      }
    });
  }

  categoryFilter(categoryId){
    if(categoryId === "all"){
      this.categoryIds = this.allCategoryIds;
    } else {
      this.categoryIds =[categoryId];
    }
    this.from = 0;
    this.currentPage = 1;
    this.totalPages = 1;
    this.getTotalPages(this.categoryIds);
    console.log(this.categoryIds);
  }

  inc(){
    this.currentPageStream.next(++this.currentPage);
  }

  dec(){
    this.currentPageStream.next(--this.currentPage);
  }

  getTotalPages(categoryIds){
    this.productService.getTotalPagesByCategoryIds(categoryIds).on('value', data => {
      if(data.val()){
        console.log(data.val());
        let items = data.val();
        let totalPages = Math.ceil(items / this.itemsOnPage);
        this.zone.run(() => {
          this.totalPages = totalPages;
        });
        
      }
    });
  }

}
