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;
  errorYear: boolean;
  searchKey:string;
  imageServer: any;
  productArray: any[] = new Array();
  productBrand: any;
  brandArr: any[] = new Array();
  sliderMinvalue: number;
  sliderhighValue: number;
  slideroptions: Options;
  page: number = 1;
  total_page: number = 1;
  filterParam: any = new Array();
  modelDates: number[] = new Array();
  carBrands:any;
  carModel:any;
  vehiBrand:any;
  vehiModel:any;
  vehiYear:any;
  modelName:any;
  modelShow :boolean;
  carFilter: any = new Array();
  carTrim:any;
  constructor(
    private router        : Router, 
    private route         : ActivatedRoute,
    public webService     : WebService
  ){ 
    this.loader = true;
    this.errorYear = false;
    this.modelShow = false;
    this.productArray = [];
    this.filterParam = {"key":'',"brand_id":Array(),"minPrice":'',"maxPrice":'','page':1};
    this.imageServer = ImageStorage;
    
    route.params.subscribe(val => {
      this.route.queryParams.subscribe(params => {
        this.searchKey = params['key'];
        this.filterParam.key = this.searchKey;
        this.filterParam.page = this.page;
        if(this.searchKey){
          this.getProductDetails(this.filterParam);
        }

        if(params['car_id']){
          this.carFilter['car_id'] = params['car_id'];
          this.purchaseFilter();
        }
      });
    });
    if(this.searchKey == ''){
      this.goToPage('purchaseHome','');
    }
  }
  
  public scrollbarOptions = { axis: 'y', theme: 'minimal-dark' };

  ngOnInit() {
    this.getBrand();
    this.getYear();
    this.getVehBrand();
  }

  getYear(){
    let currentYear = Number((new Date()).getFullYear());
    let startingYear = currentYear - 110;
    for (let date = currentYear ; date >= startingYear ; date --) {
      this.modelDates.push(date);
    }
  }

  getVehBrand(){
    this.loader=true;
      this.webService.get_data('getVehicleBrand').subscribe(response => { 
        if(response.status == 'success'){
          this.carBrands = response.data;
        }
        this.loader = false;
      });
  }

  get_model(brand_id) {
    this.vehiBrand = brand_id;
    if(!this.vehiYear){
      this.errorYear = true;
      return false;
    }
    this.carTrim = this.carModel = [];
    this.page = 1;
    this.loader = true;
    this.vehiBrand = brand_id;
    this.webService.post_data('getVehicleModel',{'vehBrand_id':this.vehiBrand,'type':0,'vehiYear':this.filterParam.year}).subscribe(response => { 
      if(response.status == 'success'){
        this.modelShow = true;
        this.carModel = response.data;
        this.filterParam.page = this.page;
        this.filterParam.maker = brand_id;
        this.getProductDetails(this.filterParam);
      }
      this.loader = false;
    });
  }

  getModelResult(modelId){
    this.vehiModel = this.filterParam.model = modelId;
    this.loader = true;
    this.page = 1;
    this.filterParam.page = this.page;
    this.webService.post_data('getVehicleTrim',{'vehBrand_id':this.vehiBrand,'vehiYear':this.vehiYear,'vehiModel':this.vehiModel}).subscribe(response => { 
      if(response.status == 'success'){
        this.carTrim = response.data;
      }
      this.loader = false;
    })
    this.getProductDetails(this.filterParam);
  }

  getTrimData(trim){
    this.page = 1;
    this.filterParam.page = this.page;
    this.filterParam.trim = trim;
    this.getProductDetails(this.filterParam);
  }

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

  getProductDetails(params:any = Array()){
    this.loader = true;
    this.webService.post_data('productSearch',params).subscribe(response => {
      if(response.status == 'success'){
        this.total_page = response.meta.total_pages;
        if(params.page == 1){
          this.productArray = response.data;
        } else {
          let thisObj = this;
          response.data.forEach(function(product,key) {
            thisObj.productArray.push(product);
          });
        }

      } else {
        this.productArray = [];
      }
      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 };
      }
    });
  }

  onScroll(){
    if(this.total_page == this.page){
      return false;
    }
    this.page += 1;
    this.filterParam.page = this.page;
    this.getProductDetails(this.filterParam);
  }

  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.page = 1;
    this.filterParam.page = this.page;
    this.filterParam.brand_id = this.brandArr;
    this.getProductDetails(this.filterParam);
  }

  getPrice(low,top){
    this.page = 1;
    this.filterParam.page = this.page;
    this.filterParam.minPrice = low;
    this.filterParam.maxPrice = top;
    this.getProductDetails(this.filterParam);
  }

  get_year(year){
    this.carModel = this.carTrim = [];
    this.page = 1;
    this.filterParam.page = this.page;
    this.filterParam.year = year;
    this.vehiYear = year;
    this.errorYear = false;
    this.getProductDetails(this.filterParam);
    if(this.vehiBrand){
      this.get_model(this.vehiBrand);
    }
    if(this.vehiModel){
      this.getModelResult(this.vehiModel);
    }
  }

  purchaseFilter(){
    if(this.carFilter['car_id']){
      this.getCustVehDetails(this.carFilter['car_id']);
      this.filterParam.car_id = this.carFilter['car_id'];
      this.getProductDetails(this.filterParam);
    }
  }

  getCustVehDetails(carId){
    this.loader = true;
    this.webService.post_data('getCustVehDetails',{'car_id':carId}).subscribe(response => {
      if(response.status == 'success'){ 
        this.filterParam.maker = this.carFilter['make'] = response.data.veh_brand_id;
        this.vehiModel = this.filterParam.model = this.carFilter['model'] = response.data.veh_modal_id;
        this.filterParam.trim = this.carFilter['trim'] = response.data.trim;
        this.vehiYear = this.filterParam.year = this.carFilter['year'] = response.data.year;
      }
      this.loader = false;
      this.get_model(response.data.veh_brand_id);
      this.getModelResult(this.vehiModel);
    })
  }

}
