"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var igd_productdata_1 = require("@intelligentgraphics/igd.productdata");
var SessionContext_1 = require("../SessionContext");
var NotificationCenterSubscription_1 = require("../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;
};
exports.useTotalPrice = function () {
    var _a = SessionContext_1.useSessionContext(), session = _a.session, contextBasket = _a.basket;
    var providedBasket = contextBasket;
    var basket = React.useMemo(function () {
        return providedBasket !== undefined
            ? providedBasket
            : igd_productdata_1.createBasket(session);
    }, [providedBasket]);
    var _b = tslib_1.__read(React.useState(function () { return calculateTotal(basket); }), 2), total = _b[0], setTotal = _b[1];
    var update = function () {
        setTotal(calculateTotal(basket));
    };
    React.useEffect(update, [basket]);
    NotificationCenterSubscription_1.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 = exports.useTotalPrice();
    return React.createElement(React.Fragment, totalPrice);
};
TotalPriceSubscription.displayName = "TotalPriceSubscription";
exports.default = TotalPriceSubscription;
