export function syncEeaProducts() {
  if(window.updatedEeaProducts) {
    window.eeaProducts = { ...window.updatedEeaProducts };
  }

  if(window.updatedEeaCheckoutProducts) {
    window.eeaCheckoutProducts = { ...window.updatedEeaCheckoutProducts };
  }
}

export function updateEeaProducts(deliveryOrderGroups, pickupOrderGroups) {
  const { collectedGroups: deliveryProducts, lastPosition } = getProductsGroups(deliveryOrderGroups);
  const { collectedGroups: pickupProducts } = getProductsGroups(pickupOrderGroups, lastPosition);
  window.updatedEeaProducts = {
    ...deliveryProducts,
    ...pickupProducts,
  };
}

export function updateEeaCheckoutProducts(deliveryOrderGroups, pickupOrderGroups) {
  const deliveryProducts = getCheckoutProductsGroups(deliveryOrderGroups);
  const pickupProducts = getCheckoutProductsGroups(pickupOrderGroups);
  window.updatedEeaCheckoutProducts = {
    ...deliveryProducts,
    ...pickupProducts,
  };
}

function getProductsGroups(orderGroup, initialPosition) {
  let position = initialPosition || 0;
  return orderGroup.reduce((groups, group) => {
    group.entries.forEach(entry => {
      const product = getProductData(entry.product);
      product.position = position++;
      groups.collectedGroups[entry.entryNumber] = product;
      groups.position = position;
    })
    return groups;
  }, {
    collectedGroups: {},
    lastPosition: 0,
  });
}

function getCheckoutProductsGroups(orderGroup) {
  return orderGroup.reduce((collectedGroups, group) => {
    group.entries.forEach(entry => {
      const product = getProductData(entry.product);
      product.quantity = entry.quantity;
      collectedGroups[entry.entryNumber] = product;
    })
    return collectedGroups;
  }, {});
}

function getProductData(product) {
  const NOT_CLASSIFIED = 'not classified';
  return {
    name: product.name,
    id: product.code,
    price: product.price.formattedPriceWithoutCurrencySymbol || NOT_CLASSIFIED,
    brand: product.brandName || NOT_CLASSIFIED,
    category: product.categoryPath ? product.categoryPath.replace("Products/", "") : NOT_CLASSIFIED,
    variant: NOT_CLASSIFIED,
  };
}

