import { useMemo } from 'preact/hooks';
import { useApi } from './api.mjs';
import { useSubscription } from './subscription.mjs';

/**
 * Returns the full expanded details of a delivery group and automatically re-renders
 * your component when that delivery group changes.
 */
function useDeliveryGroup(deliveryGroup) {
  const {
    lines
  } = useApi();
  const cartLines = useSubscription(lines);
  return useMemo(() => {
    if (!deliveryGroup) {
      return undefined;
    }
    const deliveryGroupDetails = {
      ...deliveryGroup,
      selectedDeliveryOption: getSelectedDeliveryOption(deliveryGroup),
      targetedCartLines: getTargetedCartLines(deliveryGroup, cartLines)
    };
    return deliveryGroupDetails;
  }, [deliveryGroup, cartLines]);
}
function getSelectedDeliveryOption(deliveryGroup) {
  const {
    selectedDeliveryOption,
    deliveryOptions
  } = deliveryGroup;
  return deliveryOptions.find(option => option.handle === (selectedDeliveryOption === null || selectedDeliveryOption === void 0 ? void 0 : selectedDeliveryOption.handle));
}
function getTargetedCartLines(deliveryGroup, lines) {
  const fullTargetedCartLines = [];
  for (const targetedLine of deliveryGroup.targetedCartLines) {
    const line = lines.find(line => line.id === targetedLine.id);
    if (line) fullTargetedCartLines.push(line);
  }
  return fullTargetedCartLines;
}

export { useDeliveryGroup };
