import { Component, OnInit } from '@angular/core';
import { environment } from '../../environments/environment';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-product-shop',
  templateUrl: './product-shop.component.html',
  styleUrls: ['./product-shop.component.scss']
})


export class ProductShopComponent implements OnInit {
  showNav: boolean;
  showMenu = environment.showLandingpageMenu;
  dev_url=environment.hostUrl;
  url: string;
  userData: any;
  logo_1: string;
  organisationName: any;
  supportContact: any;
  text: any;
  backgroundImage: string;
  requestDemo : boolean = false; 
  demoString = "Demo Request"; 
  cpn_showLink: boolean =false;
  showLink: boolean;
  mainSiteurl:any; 
  saanvi_showLink: boolean = false;
  cartButton = false;

  ProductArr =[];
  data_descip: string;

  constructor(private dataService: ContactService,private router: Router) { 
    let split1 = document.URL.split('//')[1];
    let split2 = split1.split('/')[0]; 
        
    if(split2 == "www.oneqlik.in"){ 
      this.showLink = true;
      this.mainSiteurl  = 'https://www.oneqlik.in/telematics/';
      this.backgroundImage = '../../assets/image/login_bg.jpg';
      this.logo_1  = '../../assets/image/f_logo.jpg' ; 
    }else{  
      console.log("Inside showlink false");
      this.showLink = false;
    }

    if(split2 == "login.cpntrack.com"){ 

      this.cpn_showLink = true;
      this.mainSiteurl  = 'http://www.cpntrack.com/';
    
    }

    if((split2 == "saanvisecurity.in")||(split2 == "www.saanvisecurity.in")){
      this.saanvi_showLink = true;
      this.mainSiteurl  = 'http://site.saanvisecurity.in';
    }
   
  }


cartValue=[];
  ngOnInit() {
    let split1 = document.URL.split('//')[1];
    let split2 = split1.split('/')[0];
    this.url = split2;

    this.dataService.dealerInfo(this.url).subscribe(
      data => {
        this.userData = data 
      if(this.url != 'www.oneqlik.in'){    
        this.logo_1    =  this.dev_url+this.userData.logo; 
      }
      
        this.organisationName = (this.url == 'www.oneqlik.in')?'OneQlik':this.userData.organisationName  ; 
        this.supportContact = this.userData.contact_support?this.userData.contact_support : ''; 


        this.text=this.userData.text;
       
      },err=>{
        this.backgroundImage = '../../assets/image/login_bg.jpg' ;
     
      }) 

    
    for(var i = 0; i <this.showMenu.length;i++){
      if (this.url == this.showMenu[i]) {
        this.showNav = true;
        return;
      } else {
        this.showNav = false;
      }
    }

    this.getProducts();
  

  }
  message:any;

  getADemoReq(){
    this.router.navigateByUrl("login");
  }


  addtocart(productObject){
    productObject['addToCart'] = true;
    // this.cartValue=[];
    this.cartValue.push(productObject);
    console.log(this.cartValue);
    // productObject['cartValue'] = this.cartValue ; 
    localStorage.setItem('addedToCart',JSON.stringify(this.cartValue));
    // this.router.navigateByUrl("product-shop/product-overview");
    this.data_descip = 'Product added to Cart';
    function launch_toast() {
      // console.log(divid);
      var x = document.getElementById("toast")
      //console.log(x);
      x.className = "show";
      setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
   
    }


    launch_toast();
  }

  removeFromCart(pOj){
    pOj['addToCart'] = false;
    this.data_descip = 'Product Removed from Cart';
    var padded  =  localStorage.getItem('addedToCart');
    console.log('productAdded',padded);
    if(padded != undefined){
      var prodAdd = JSON.parse(padded);
      for(var  y = 0 ; y<(prodAdd).length; y++){
        if(pOj.raw._id  === prodAdd[y].raw._id){
          prodAdd.splice(y,1);
          localStorage.setItem('addedToCart',JSON.stringify(prodAdd));
        }
      }
    }

    function launch_toast() {
      // console.log(divid);
      var x = document.getElementById("toast")
      //console.log(x);
      x.className = "show";
      setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
   
    }
    launch_toast();


  }

  showProductDetail(pObj){
    localStorage.setItem('products',JSON.stringify(pObj)); 
    this.router.navigateByUrl("product-shop/product-overview");
  }



  getProducts(){
    this.ProductArr = [];
    this.dataService.getProducts().subscribe(res=>{
      console.log('productDetail=>',res);
      var tempArr = res;
      for(var i=0;i< tempArr.length;i++){
        var tempObj ={
          device_name : tempArr[i].Product_name,
          price : tempArr[i].price ,
          discountPrice : getdisCountPrice(tempArr[i].discount_price,tempArr[i].price),
          imageUrl : getImageUrl(tempArr[i].Images,tempArr[i].productImages),
          raw : tempArr[i],
          addToCart:false
        }
        this.ProductArr.push(tempObj);

      }
  
      var productAdded  =  localStorage.getItem('addedToCart');
      console.log('productAdded',productAdded);
      if(productAdded != undefined){
            var crtVal = JSON.parse(productAdded);
            console.log(crtVal);
           for(var j = 0 ; j<crtVal.length;j++){
           
            this.cartValue.push(crtVal[j]);    
            for(var z=0;z<this.ProductArr.length;z++){
              if(this.ProductArr[z].raw._id === crtVal[j].raw._id){
                console.log("Inside Right Function");
                this.ProductArr[z].addToCart = crtVal[j].addToCart;
              }
            }  
          }
      }
      console.log('this.ProductArr',this.ProductArr);
      //   if(this.message.cartValue != undefined){
      //     for(var j = 0 ; j<this.message.cartValue.length;j++){
      //       this.cartValue.push(this.message.cartValue[j]);
      //     }
      //   }     
     console.log(this.ProductArr);
    })
    function getdisCountPrice(dPrice,price){
      if((dPrice === undefined)||(price === undefined)){
            return 0;
      }else if((dPrice === undefined)){
        return price.toFixed(2);

      }else{
        var numVal1 = Number(price);
        var numVal2 = Number(dPrice) / 100;
        var totalValue = numVal1 - (numVal1 * numVal2) ; 
        return totalValue.toFixed(2);
      }

    }


    function getImageUrl(i1,i2){
      var tArr = [];
      if(i1 != undefined){
        tArr = i1;
      }
      if(i2 != undefined){
        tArr = i2;
      }            
       
      if(tArr.length === 0){
        var urlDefault ='../../assets/image/noImage.png'
          return [urlDefault];
      }else{
        return urlLink();
      }

      function urlLink(){
        for(var j =0 ; j <tArr.length ; j++){
          var str = 'http://www.oneqlik.in/';
          var shortenUrl = tArr[j].split('/');
          var shortenUrl_1 = shortenUrl[1] + '/' + shortenUrl[2] + '/' + shortenUrl[3];
          var furl = str + shortenUrl_1 ; 
        }
     
        return [furl] ; 
      }
                
    }
    
  }

  // getProduct_overview(){

  //   this.router.navigateByUrl("product-shop/product-overview");

  // }

  
}
