const LAST_VISITED_PRODUCTS_KEY = 'js-shop-products-last-visited';

const getStorage = (): number[] => {
   const storage = localStorage.getItem(LAST_VISITED_PRODUCTS_KEY);
   if(!storage) {
      return [];
   }
   return JSON.parse(storage);
}

const saveToStorage = (products: number[]) => {
   localStorage.setItem(LAST_VISITED_PRODUCTS_KEY, JSON.stringify(products));
}

const add = (id: number) => {
   const products = getStorage().filter((val: number) => val != id);
   products.unshift(id);
   saveToStorage(products);
}

const get = (excludeId: number): number[] => {
   return getStorage().filter((val: number) => val != excludeId);
}

const initExternal = () => {
   window.wpj.jsShop.lastVisitedProducts = {
      add(id: number) { add(id);},
      get(excludeId: number): number[] {return get(excludeId);}
   };
}

export const LastVisitedProducts = {
   initExternal,
   get,
   add
}
