'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var hooks = require('preact/hooks');
var api = require('./api.js');
var subscription = require('./subscription.js');

/**
 * 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
  } = api.useApi();
  const cartLines = subscription.useSubscription(lines);
  return hooks.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;
}

exports.useDeliveryGroup = useDeliveryGroup;
