import * as React from "react";
import { createBasket } from "@intelligentgraphics/igd.productdata";
import { useSessionContext } from "../SessionContext";
import { useNotificationCenterSubscription } from "../NotificationCenterSubscription";
const calculateTotal = (basket) => {
    const totals = basket.getBomTotals();
    const totalEntry = totals.find(entry => entry.type === "total");
    if (!totalEntry) {
        throw new Error(`Total calculation requires one entry with a type of "total" to be returned by the basket.`);
    }
    return totalEntry.text;
};
export const useTotalPrice = () => {
    const { session, basket: contextBasket } = useSessionContext();
    const providedBasket = contextBasket;
    const basket = React.useMemo(() => providedBasket !== undefined
        ? providedBasket
        : createBasket(session), [providedBasket]);
    const [total, setTotal] = React.useState(() => calculateTotal(basket));
    const update = () => {
        setTotal(calculateTotal(basket));
    };
    React.useEffect(update, [basket]);
    useNotificationCenterSubscription({
        onItemCreated: update,
        onItemChanged: update,
        onItemRemoved: update,
    });
    return total;
};
/**
 * Renders the total price of a session as a string
 *
 * @param {*} props
 * @returns
 */
const TotalPriceSubscription = props => {
    const totalPrice = useTotalPrice();
    return React.createElement(React.Fragment, totalPrice);
};
TotalPriceSubscription.displayName = "TotalPriceSubscription";
export default TotalPriceSubscription;
