import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { NgxGalleryOptions, NgxGalleryImage, NgxGalleryAnimation } from 'ngx-gallery';
import { WebService } from '../../provider/web.service';
import { NgxCarousel } from 'ngx-carousel';
import { ImageStorage } from '../../../environments/server.config';
import { SubjectService } from '../../provider/subject.service';
import * as $ from 'jquery';

@Component({
  selector: 'app-productdetails',
  templateUrl: './productdetails.component.html',
  styleUrls: ['./productdetails.component.scss']
})
export class ProductdetailsComponent implements OnInit {
  
  loader: boolean;
  loader2:boolean;
  review_loader:boolean;
  count:any;
  product_id: number;
  imageServer: string;
  productDetails:any;
  product_data:any = new Array();
  galleryImages: NgxGalleryImage[];
  galleryOptions: NgxGalleryOptions[];
  loginDetails:any;
  trendingProductData:any;
  page: number = 1;
  reviewArray:any = new Array();
  total_page: number = 1;
  cartValue :number = 1;

  @ViewChild("indexLoginModal") loginModalRef: ElementRef;

  public carouselTile: NgxCarousel;
  constructor(private router: Router, 
              private route: ActivatedRoute,
              public webService: WebService,
              public subjectService : SubjectService) {
                
    this.loader       = true;
    this.loader2       = true;
    this.count        = 1;
    this.product_id   = 0;
    this.imageServer  = ImageStorage; 
    this.router.routeReuseStrategy.shouldReuseRoute = function(){
      return false;
    }

    route.params.subscribe(val => {
      this.route.queryParams.subscribe(params => {
        this.product_id = params['product_id'];
      });
    });

    if(!this.product_id){
      this.goToPage('purchaseHome','');
    }
  }

  add(){this.count = this.count + 1;}
  minus(){this.count = this.count - 1;
    if(this.count < 1){this.count = 1;}
  }
  
  ngOnInit(): void {
    
    this.designModules();
    this.checkUserLogin();
    this.trendingProducts();
    this.getProductDetails();
  }

  checkUserLogin(){
    this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    this.subjectService.getLoginData().subscribe(loginData => {
      this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    });
  }

  getProductDetails(){
    this.loader = true;
    let user_id: number = 0;
    if(this.loginDetails && this.loginDetails.customer_id){
      user_id = this.loginDetails.customer_id;
    }
    this.webService.post_data('SingleProductSearch',{"product_id":this.product_id,'page':this.page,'user_id':user_id}).subscribe(response => {
      if(response.status == 'success'){
        let image: string = '';
        let imageArr: any[] = new Array();
        const thisObj = this;
        this.productDetails = response.data;
        this.reviewArray = response.data.reviews.data;
        this.total_page = response.data.reviews.meta.total_pages;
        this.cartValue = (this.productDetails.cart_id > 0) ? 2 : 1;
        if(this.productDetails.images.length > 0){
          thisObj.productDetails.images.forEach(function (data) {
            image = thisObj.imageServer + data.image;
            imageArr.push({small: image,medium: image,big: image});
          });
        }else{
          image = thisObj.imageServer +'assets/images/no_image_text.png';
          imageArr.push({small: image,medium: image,big: image});
        }
        this.galleryImages = imageArr;
      }else{
        this.productDetails = false;
      }
      this.loader = false;
    });
  }

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

    this.page += 1;    
    this.review_loader = true;
    this.webService.post_data('SingleProductSearch',{"product_id":this.product_id,'page':this.page}).subscribe(response => {
      if(response.status == 'success'){
        let thisObj = this;
        response.data.reviews.data.forEach(function(reviewData,key) {
          thisObj.reviewArray.push(reviewData);
        });
      }
      this.review_loader = false;
    });
  }

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

  buyProduct(amount){
    if(!this.loginDetails){
      this.loginModalRef.nativeElement.click();
      return false;
    }
    this.product_data = {amount:amount,product_id:this.product_id,quantity:this.count,total_amount:this.count*amount};
    this.webService.setLocalStorageItem('productDetails', JSON.stringify(this.product_data));
    this.goToPage('address','');
  }

  addToCart(amount){
    if(!this.loginDetails){
      this.loginModalRef.nativeElement.click();
      return false;
    }
    this.loader=true;
    this.product_data = {product_id:this.product_id,quantity:this.count,amount:this.count*amount,customer_id:this.loginDetails.customer_id};
    this.webService.post_data('addToCart',this.product_data).subscribe(response => {
      if(response.status == 'success'){
        if(response.data > 0){
          this.cartValue = 2;
        }
      }
      this.loader = false;
    });
  }

  goCart(){
    this.goToPage('cart','');
  }

  latestPrdtDtls(prdt_id){
    this.goToPage('productdetails',{"product_id":prdt_id});
  }
  
  goToPage(path,data=null){
    this.router.navigate([path],{queryParams:  data});
    document.body.scrollTop  =  document.documentElement.scrollTop  =  0;
  }
  
  designModules(){
    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', loop: true}
    this.galleryOptions = [
      {
        width: '100%',
        height: '570px',
        thumbnailsColumns: 4,
        imageAnimation: NgxGalleryAnimation.Slide
      },
      {
        breakpoint: 1440,
        width: '100%',
        height: '400px',
        imagePercent: 80,
        thumbnailsPercent: 20,
        thumbnailsMargin: 20,
        thumbnailMargin: 20
      },
      {
        breakpoint: 400,
        preview: false
      }
    ];
  }
  carouselTileLoad(){ return ''; }
}
  