"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TxConfirmModal = void 0;
const react_1 = __importStar(require("react"));
const polymesh_ui_1 = require("@polymathnetwork/polymesh-ui");
const polymesh_sdk_1 = require("@polymathnetwork/polymesh-sdk");
const react_i18next_1 = require("react-i18next");
const definition_1 = require("./definition");
const calcTxCost_1 = require("../utils/calcTxCost");
const formatters = __importStar(require("../utils/formatters"));
const heap = __importStar(require("../analytics/heap"));
exports.TxConfirmModal = ({ store, appStateActions, transactionActions, tokenSymbol }) => {
    const { t } = react_i18next_1.useTranslation(definition_1.TranslationNS.ConfirmModal);
    const [protocolFees, setProtocolFees] = react_1.useState(undefined);
    const [gasFees, setGasFees] = react_1.useState(undefined);
    const { dispatch, getState } = store;
    const { transaction: { signingPackage }, polymesh: { selectedAccount, accountBalances, inFlight }, } = getState();
    const { confirmationStatus, confirmationData, queue, apiQueue, id: signingPackageId, } = signingPackage || {};
    const isApi = !!apiQueue;
    const balances = accountBalances[selectedAccount];
    const enoughBalance = balances === null || balances === void 0 ? void 0 : balances.available.gte((protocolFees === null || protocolFees === void 0 ? void 0 : protocolFees.plus(gasFees || 0)) || 0);
    const hasFees = new polymesh_sdk_1.BigNumber(protocolFees || 0).toNumber() > 0;
    react_1.useEffect(() => {
        const getFees = () => __awaiter(void 0, void 0, void 0, function* () {
            if (!queue) {
                setProtocolFees(undefined);
                setGasFees(undefined);
            }
            else if (isApi) {
                const cost = yield calcTxCost_1.calcTxCost(queue, selectedAccount || '');
                setGasFees(cost);
                setProtocolFees(confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.apiProtocolFee);
            }
            else {
                const fees = yield queue.getMinFees();
                setProtocolFees(fees.protocol);
                setGasFees(fees.gas);
            }
        });
        getFees();
    }, [queue]); // eslint-disable-line
    const setConfirmationStatus = (status) => {
        dispatch(transactionActions.setConfirmationStatus(status));
    };
    const renderItem = (item, itemIndex, isLastItem) => {
        var _a;
        let formattedValue = item.value;
        if (item.value instanceof Date) {
            formattedValue = formatters.toDateString(item.value);
        }
        else if (item.value && item.translate) {
            formattedValue = t(formattedValue);
        }
        else if (item.value && item.value.toString().length > 25) {
            formattedValue = formatters.shortenString((_a = item.value) === null || _a === void 0 ? void 0 : _a.toString(), {
                size: 25,
            });
        }
        return (react_1.default.createElement(react_1.Fragment, { key: itemIndex },
            react_1.default.createElement(polymesh_ui_1.Flex, Object.assign({ justifyContent: "space-between" }, (isLastItem ? {} : { mb: 'm' })),
                react_1.default.createElement(polymesh_ui_1.Text, { variant: "b1m", color: "gray.2" }, t(`${item.label}`)),
                item.link ? (react_1.default.createElement(polymesh_ui_1.Link, { id: `confirm_modal_item_link_${itemIndex}`, href: item.link }, formattedValue)) : (react_1.default.createElement(polymesh_ui_1.Text, { variant: "b1m", color: "highlightText" }, formattedValue || '[None]'))),
            ((!isLastItem && item.hr !== false) || item.hr) && (react_1.default.createElement(polymesh_ui_1.Hr, { color: "gray.4" }))));
    };
    const renderSectionItems = (items) => {
        return items.map((item, index) => renderItem(item, index, index + 1 === items.length));
    };
    const renderSections = (sections) => sections.map((section, index) => (react_1.default.createElement(react_1.Fragment, { key: `section${index.toString()}` },
        section.label && (react_1.default.createElement(polymesh_ui_1.Box, null,
            react_1.default.createElement(polymesh_ui_1.Heading, { variant: "h5", mb: "m", mt: "4" }, t(`${section.label}`)))),
        renderSectionItems(section.items))));
    const onCancel = () => {
        setConfirmationStatus(definition_1.ConfirmationStatus.None);
        if (inFlight)
            dispatch(appStateActions.setAsync(false));
    };
    return (react_1.default.createElement(polymesh_ui_1.Modal, { isCloseable: false, isOpen: confirmationStatus === definition_1.ConfirmationStatus.Pending, maxWidthContainer: 750 },
        react_1.default.createElement(polymesh_ui_1.Modal.Body, { width: 656 },
            react_1.default.createElement(polymesh_ui_1.Box, null,
                react_1.default.createElement(polymesh_ui_1.Heading, { variant: "h5" }, t(`${confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.title}`, confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.titleArgs))),
            (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.message) && (react_1.default.createElement(polymesh_ui_1.Box, null,
                react_1.default.createElement(polymesh_ui_1.Paragraph, { mt: 20 }, t(`${confirmationData.message}`, confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.messageArgs)))),
            (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.body) && react_1.default.createElement(polymesh_ui_1.Box, { mt: "m" }, confirmationData.body),
            (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.sections) && (react_1.default.createElement(polymesh_ui_1.Box, { mt: "l" }, renderSections(confirmationData.sections))),
            (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.footer) && (react_1.default.createElement(polymesh_ui_1.Box, { mt: "m" }, confirmationData.footer))),
        react_1.default.createElement(polymesh_ui_1.Modal.Footer, null,
            react_1.default.createElement(polymesh_ui_1.Flex, { justifyContent: hasFees ? 'space-between' : 'flex-end' },
                hasFees && (react_1.default.createElement(polymesh_ui_1.Flex, { flexDirection: "column", alignItems: "flex-start" },
                    react_1.default.createElement(polymesh_ui_1.Flex, { flex: 1, flexDirection: "row", justifyContent: "space-between", mt: "1" },
                        react_1.default.createElement(polymesh_ui_1.Box, null,
                            react_1.default.createElement(polymesh_ui_1.Text, { variant: "b3m", color: "gray.2" }, "Total cost")),
                        react_1.default.createElement(polymesh_ui_1.Box, { mb: 1, ml: "s" },
                            react_1.default.createElement(polymesh_ui_1.TooltipIcon, { content: "This will be withdrawn from your wallet balance.", iconButtonProps: {
                                    buttonProps: {
                                        onMouseEnter: heap.hover({
                                            id: 'confirm_modal_cost_tooltip',
                                        }),
                                    },
                                } }))),
                    react_1.default.createElement(polymesh_ui_1.Box, null,
                        react_1.default.createElement(polymesh_ui_1.Text, { variant: "b2m", color: "gray.1" }, formatters.formatAmount(protocolFees || new polymesh_sdk_1.BigNumber(0))),
                        react_1.default.createElement(polymesh_ui_1.Text, { variant: "b2m", color: "gray.2" }, ` ${tokenSymbol}`)))),
                !enoughBalance && (react_1.default.createElement(polymesh_ui_1.Text, { color: "alert", fontSize: "0", fontWeight: "bold", width: "15%", mr: "m" }, "Insufficent funds available")),
                react_1.default.createElement(polymesh_ui_1.Box, null,
                    react_1.default.createElement(polymesh_ui_1.ButtonLarge, { id: `${signingPackageId}_confirm_modal_cancel_button`, variant: "secondary", onClick: onCancel }, t('General:cancel')),
                    react_1.default.createElement(polymesh_ui_1.ButtonLarge, { id: `${signingPackageId}_confirm_modal_confirm_button`, disabled: !enoughBalance, onClick: () => setConfirmationStatus(definition_1.ConfirmationStatus.Done) }, (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.submitButtonTitle) || t('General:confirm')))))));
};
//# sourceMappingURL=TxConfirmModal.js.map