import { SELLERS_LIST_CACHE_KEY } from '@assets/js-shop/sellers/data/SellerAvailabilityListData';
import { clearPersistedMapStorage, IPersistedMap } from '@assets/js-shop/components/hooks/usePersistedMap';
import { SELLERS_DETAIL_CACHE_KEY } from '@assets/js-shop/sellers/data/SellerAvailabilityDetailData';

export interface ISellerCacheableElement {
   productId: number;
   element: HTMLElement,
}

export function findNewSellerElements (selector: string, cacheMap: IPersistedMap<number>)  {
   const DomElements = document.querySelectorAll(selector) as NodeListOf<HTMLElement>;
   const cachedItems: ISellerCacheableElement[] = [];
   const itemsToFetch: Map<number, ISellerCacheableElement> = new Map();

   DomElements.forEach((element: HTMLElement) => {
      const productId: number = Number(element.dataset.productId);

      if (cacheMap.has(productId)) {
         cachedItems.push({ productId, element });
      } else {
         itemsToFetch.set(productId, { productId, element });
      }

   });

   return { cachedItems, itemsToFetch };
}


export const sellersClearCache = () => {
   clearPersistedMapStorage(SELLERS_LIST_CACHE_KEY);
   clearPersistedMapStorage(SELLERS_DETAIL_CACHE_KEY);
};
