import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { Options } from 'ng5-slider';
import { WebService } from '../../provider/web.service';
import { ImageStorage } from '../../../environments/server.config';

@Component({
  selector: 'app-productlist',
  templateUrl: './productlist.component.html',
  styleUrls: ['./productlist.component.scss']
})
export class ProductlistComponent implements OnInit {
  loader: boolean;
  searchKey:string;
  imageServer: any;
  productArray: any;
  productBrand: any;
  brandArr: any[] = new Array();
  sliderMinvalue: number;
  sliderhighValue: number;
  slideroptions: Options;

  constructor(
    private router        : Router, 
    private route         : ActivatedRoute,
    public webService     : WebService
  ){ 
    this.loader = true;
    this.productArray = true;

    this.imageServer = ImageStorage;
    route.params.subscribe(val => {
      this.route.queryParams.subscribe(params => {
        this.searchKey = params['key'];
        this.getProductDetails({"key":this.searchKey});
      });
    });
    if(this.searchKey == ''){
      this.goToPage('purchaseHome','');
    }
  }
  
  public scrollbarOptions = { axis: 'y', theme: 'minimal-dark' };

  ngOnInit() {
    this.getBrand();
  }

  goToPage(path,data=null){
    this.router.navigate([path],{queryParams:  data});
    document.body.scrollTop  =  document.documentElement.scrollTop  =  0;
  }

  getProductDetails(params:any = ''){
    this.loader = true;
    this.webService.post_data('productSearch',params).subscribe(response => {
      if(response.status == 'success'){
        console.log(response.data);
        this.productArray = response.data;
      } else {
        this.productArray = false;
      }
      this.loader = false;
    });
  }

  getBrand(){
    this.webService.get_data('getBrands').subscribe(brandResponse => {
      if(brandResponse.status == 'success'){
        this.productBrand = brandResponse.brands;
        this.sliderMinvalue = 0;
        this.sliderhighValue = brandResponse.maxamount;
        this.slideroptions = { floor: 0, ceil: brandResponse.maxamount, step: 100 };
      }
    });
  }

  getSingleProductDetails(prdt_id){
    this.goToPage('productdetails',{"product_id":prdt_id});
  }

  selectBrand(event,brand_id){
    if (event.target.checked) {
      this.brandArr.push(brand_id);
    } else {
      let id = this.brandArr.findIndex(x => x == brand_id);
      if (id != -1) {
        this.brandArr.splice(id, 1);
      }
    }
    this.getProductDetails({"key":this.searchKey,"brand_id":this.brandArr});
  }

  getPrice(low,top){
    this.getProductDetails({"key":this.searchKey,"brand_id":this.brandArr,"minPrice":low,"maxPrice":top});
  }
}
