class WpjLastVisitedProducts {
   getStorage() {
      const storage = localStorage.getItem('products_last_visited');
      if(!storage) {
         return {products:[]};
      }
      return JSON.parse(storage);
   }

   removeProduct(productsIds, productId) {
      return productsIds.filter((val) => val != productId);
   }

   saveToStorage(object) {
      localStorage.setItem('products_last_visited', JSON.stringify(object));
   }

   addLastVisitedProduct(productId) {
      const storage = this.getStorage();
      storage.products = this.removeProduct(storage.products, productId).slice(0, 7);
      storage.products.unshift(productId);
      this.saveToStorage(storage);
   }

   initLazy(element, currentProductId, params = {}) {
      let me = this;
      function observeElement(entries) {
         entries.forEach(entry => {
            if (entry.isIntersecting) {
               me.loadLastVisitedBlock(entry.target, currentProductId, params);
               observer.unobserve(entry.target);
            }
         });
      }

      const observerOptions = {
         rootMargin: '300px 0px 300px 0px'
      };

      const observer = new IntersectionObserver(observeElement, observerOptions);
      observer.observe(element);
   }

   loadLastVisitedBlock(element, currentProductId, params = {}) {
      const storage = this.getStorage();
      storage.products = this.removeProduct(storage.products, currentProductId);

      if (storage.products.length <= 0) {
         return;
      }

      const urlParams = Object.assign({
         products: JSON.stringify(storage.products),
      }, params);

      fetch('/_kupshop/lastvisited/?' + new URLSearchParams(urlParams),{
         method: 'GET',
         headers: {
            'Content-Type': 'application/json',
         },
         redirect: 'follow',
      }).then((response) => {
         // Examine the text in the response
         response.json().then((data) => {
            element.innerHTML = data.html;
            $('body').trigger('lastVisitedProductsLoaded');
         });
      });
   }

}

wpj.lastVisitedProducts = new WpjLastVisitedProducts();
