import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NgxCarousel } from 'ngx-carousel';
import { WebService } from '../../provider/web.service';
import { ImageStorage } from '../../../environments/server.config';
import { Router,ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {
  count:any;
  loginDetails:any;
  loader:boolean;
  cartData:any;
  page :number = 1;
  total_page :number = 1;
  imageServer: any;
  trend_loader:boolean;
  trendingProductData:any;
  product_data:any;
  cartQuantity :any[] = new Array();
  confirmParam: string = '';
  confirmCallBak: string = '';

  @ViewChild("confirmModal") public confirmModalRef: ElementRef;

  public carouselTile: NgxCarousel;
  constructor(
    private router        : Router, 
    private route         : ActivatedRoute,
    public webService     : WebService
  ) { 
    this.count = 1;
    this.loader = true;
    this.imageServer = ImageStorage;
    this.trend_loader = true;
  }

  add(cart_id: number){
    if(this.cartQuantity[cart_id] && this.cartQuantity[cart_id]['quantity'] < 15){
      this.cartQuantity[cart_id]['quantity'] = this.cartQuantity[cart_id]['quantity']+1;
      this.cartQuantity[cart_id]['total_amount'] = this.cartQuantity[cart_id]['amount']*this.cartQuantity[cart_id]['quantity'];
    }
  }

  minus(cart_id: number){
    if(this.cartQuantity[cart_id] && this.cartQuantity[cart_id]['quantity'] > 1){
      this.cartQuantity[cart_id]['quantity'] = this.cartQuantity[cart_id]['quantity']-1;
      this.cartQuantity[cart_id]['total_amount'] = this.cartQuantity[cart_id]['amount']*this.cartQuantity[cart_id]['quantity'];
    }
  }

  ngOnInit() {
    this.checkUserLogin();
    this.getCartData();
    this.trendingProducts();
    this.carouselTile = {grid: {xs: 1, sm: 2 , md: 4, lg: 8, all: 0},slide: 1, speed: 400,point: { visible: false },load: 2, touch: true, easing: 'ease'}
  }

  checkUserLogin(){
    this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    if(!this.loginDetails){
      this.goToPage('purchaseHome','');
    }
  }

  getCartData(){
    if(!this.loginDetails || !this.loginDetails.customer_id){
      return false;
    }
    this.loader = true;
    this.webService.post_data('getCartData',{'customer_id':this.loginDetails.customer_id,'page':this.page}).subscribe(response => {
      if(response.status == 'success'){
        this.cartData = response.data;
        const thisObj = this;
        let tempArr:any = Array();
        this.cartData.forEach(function(data,key) {
          tempArr[data.cart_id] = {'quantity':+data.quantity,'amount':data.amount,'total_amount':data.quantity*data.amount};
        });
        thisObj.cartQuantity = tempArr;
      }else{
        this.cartData = false;
      }
      this.loader = false;
    })
  }

  trendingProducts(){
    this.trend_loader = true;
    this.webService.post_data('getTrendingPrdts',{'page':this.page}).subscribe(response => {
      if(response.status == 'success'){
        this.trendingProductData = response.data;
      } else {
        this.trendingProductData = false;
      }
      this.trend_loader = false;
    });
  }

  removeProduct(params){
    this.page= 1;
    this.loader = true;
    this.webService.post_data('removeCartPrdt',params).subscribe(response => {
      if(response.status == 'success'){
       this.getCartData();
      }
      this.trend_loader = false;
    });
  }

  cnfRemoveProduct(cartId){
    if(cartId < 0){
      return false;
    }
    this.showConfirmPopUp('removeProduct',{'cart_id':cartId});
  }

  showConfirmPopUp(fn_name: string, param: any){
    if(fn_name === ''){
      return false;
    }
    if(param){
      param = JSON.stringify(param);
    }
    this.confirmParam = param;
    this.confirmCallBak = fn_name;
    this.confirmModalRef.nativeElement.click();
  }

  confirmCallBack(fn_name: string,param: string){
    if(fn_name === '' || !this[fn_name]){
      return false;
    }
    if(param !== ''){
      param = JSON.parse(param);
      this[fn_name](param);
    } else {
      this[fn_name]();
    }
  }

  onScroll(){
    if(this.total_page < this.page){
      return false;
    }

    this.page += 1;    
    this.loader = true;
    this.webService.post_data('getCartData',{'customer_id':this.loginDetails.customer_id,'page':this.page}).subscribe(response => {
      if(response.status == 'success'){
        let thisObj = this;
        response.data.forEach(function(cartData,key) {
          thisObj.cartData.push(cartData);
        });
      }
      this.loader = false;
    });
  }

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

  buyProduct(product_id,total_amount,cartId,quantity,amount){
    if(cartId <= 0 || product_id <= 0 || total_amount <= 0 || quantity <= 0 || amount <= 0){
      return false;
    }
    //this.loader = true;
   // this.webService.post_data('removeCartPrdt',{'cart_id':cartId}).subscribe(response => {
     // if(response.status == 'success'){
        this.product_data = {amount:amount,product_id:product_id,quantity:quantity,total_amount:total_amount,cart_id:cartId};
        this.webService.setLocalStorageItem('productDetails', JSON.stringify(this.product_data));
        this.goToPage('address','');
     // }
     // this.loader = false;
    //});
  }

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

  carouselTileLoad(){ return ''; }

}
