import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { Http, ResponseContentType } from '@angular/http';
import { WebService } from '../../provider/web.service';
import { NgxGalleryOptions, NgxGalleryImage, NgxGalleryAnimation } from 'ngx-gallery';
import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms';
import { ValidationService } from '../../provider/validation.service';
import { NgxCarousel } from 'ngx-carousel';
import { ImageStorage } from '../../../environments/server.config';
import { Options } from 'ng5-slider';
import { apiConfig } from '../../../environments/server.config';

interface RangeSliderModel {
  minValue: number;
  maxValue: number;
  options: Options;
}

@Component({
  selector: 'app-track',
  templateUrl: './track.component.html',
  styleUrls: ['./track.component.scss']
})
export class TrackComponent implements OnInit {
  ref_id:any;
  count:any;
  loginDetails:any;
  loader:boolean;
  serverUrl:string;
  loader_review:boolean;
  imageServer: string;
  orderDetails:any;
  userReviewed:boolean;
  galleryOptions: NgxGalleryOptions[];
  galleryImages: NgxGalleryImage[];
  verticalSlider2:any;
  rateFormClick:boolean;
  rateFormResponse:any;

  @ViewChild('ratingModal') ratingModal: ElementRef;

  public carouselTile: NgxCarousel;
    constructor(private router        : Router, 
                private route         : ActivatedRoute,
                public errorMsg       : ValidationService,
                public webService     : WebService,
                private http          : Http){
      this.count = 0;
      this.loader = true;
      this.serverUrl   = apiConfig;
      this.userReviewed = true;
      this.loader_review = false;
      this.imageServer  = ImageStorage;
      this.rateFormClick = false; 
    }
    rateForm;
    ngOnInit(): void {
      this.route.queryParams.subscribe(params => {
        this.ref_id = params['ref'];
        if(!this.ref_id || this.ref_id < 0){
          this.goToPage('purchaseHome','');
        }
      });
      
      this.designModule();
      this.getOrderDetail();
      this.checkUserLogin();
      this.unsetProdDetails();

      
      this.rateForm = new FormGroup({
        rating: new FormControl('5'),
        title: new FormControl('',[Validators.required]),
        description: new FormControl('',[Validators.required])
      });
    }

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

    rateFormSubmit(data){
      if(this.rateForm.invalid){
        return false;
      }
      data.product_id = this.orderDetails.product_id;
      data.customer_id = this.loginDetails.customer_id;
      this.loader_review = true;
      const This = this;
      this.webService.post_data('rateProduct',data).subscribe(response => {
        if(response.status == 'success'){
          this.rateFormResponse = response;
          this.userReviewed = true;
          setTimeout( function() {
            This.rateFormResponse = false;
            This.ratingModal.nativeElement.click();
          }, 3000);
        }else{
          response.status = 'error';
          response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;
  
          this.rateFormResponse = response;
          setTimeout( function() {
            This.rateFormResponse = false;
          }, 3000);
        }
        this.loader_review = false;
      },error => {
        this.rateFormResponse = {'status':'error','message':this.errorMsg.errorList.req_failure};
        setTimeout( function() {
          This.rateFormResponse = false;
        }, 3000);
        this.loader_review = false;
      });
    }

    getOrderDetail(){
      this.loader = true;
      this.webService.post_data('getOrderDetail',{'ref_id':this.ref_id}).subscribe(response => {
        if(response.status == 'success'){
          let image: string = '';
          let imageArr: any[] = new Array();
          const thisObj = this;
          this.orderDetails = response.data;
          this.userReviewed = (this.orderDetails.review_id <= 0 && (this.orderDetails.odr_status == '5' || this.orderDetails.odr_status == '6' || this.orderDetails.odr_status == '7'))?false:true;
          if(this.orderDetails.images.length > 0){
            thisObj.orderDetails.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;

          if(this.orderDetails.odr_status === '2'){
            this.verticalSlider2 = { minValue: 50, maxValue: 50, options: { floor: 0, ceil: 50, vertical: true } };
          }
          else if(this.orderDetails.odr_status ==='3'){
            this.verticalSlider2 = { minValue: 50, maxValue: 76, options: { floor: 0, ceil: 76, vertical: true } };
          }
          else if(this.orderDetails.odr_status ==='4'){
            this.verticalSlider2 = { minValue: 50, maxValue: 152, options: { floor: 0, ceil: 152, vertical: true } };
          }
          else if(this.orderDetails.odr_status === '5'){
            this.verticalSlider2 = { minValue: 50, maxValue: 10000000, options: { floor: 0, ceil: 10000000, vertical: true } };
          }
        }else{
          this.orderDetails = false;
          this.goToPage('purchaseHome','');
        }
        this.loader = false;
      });
    }

    reviewBtn(){
      if(this.orderDetails.product_id <= 0){
        this.goToPage('purchaseHome','');
      }
      this.goToPage('rating',{"pId":this.orderDetails.product_id});
    }

    downloadFile(orderId){
      document.open(this.serverUrl+'','_blank');
    }

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

    carouselTileLoad(){ return ''; }
    add(){this.count = this.count + 1;}
    minus(){ this.count = this.count - 1; if(this.count < 0){ this.count = 0; }}

    designModule(){
      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'}
      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 }
      ];
    }
  }
  