import { __read } from "tslib";
import * as React from "react";
import { createBasket } from "@intelligentgraphics/igd.productdata";
import { useSessionContext } from "../SessionContext";
import { useNotificationCenterSubscription } from "../NotificationCenterSubscription";
var calculateTotal = function (basket) {
    var totals = basket.getBomTotals();
    var totalEntry = totals.find(function (entry) { return 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 var useTotalPrice = function () {
    var _a = useSessionContext(), session = _a.session, contextBasket = _a.basket;
    var providedBasket = contextBasket;
    var basket = React.useMemo(function () {
        return providedBasket !== undefined
            ? providedBasket
            : createBasket(session);
    }, [providedBasket]);
    var _b = __read(React.useState(function () { return calculateTotal(basket); }), 2), total = _b[0], setTotal = _b[1];
    var update = function () {
        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
 */
var TotalPriceSubscription = function (props) {
    var totalPrice = useTotalPrice();
    return React.createElement(React.Fragment, totalPrice);
};
TotalPriceSubscription.displayName = "TotalPriceSubscription";
export default TotalPriceSubscription;
