"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.prototype.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 jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = 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"));
const TxConfirmModal = ({ store, appStateActions, transactionActions, tokenSymbol }) => {
    const { t } = (0, react_i18next_1.useTranslation)(definition_1.TranslationNS.ConfirmModal);
    const [protocolFees, setProtocolFees] = (0, react_1.useState)(undefined);
    const [gasFees, setGasFees] = (0, 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;
    (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 (0, 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 ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)(polymesh_ui_1.Flex, Object.assign({ justifyContent: "space-between" }, (isLastItem ? {} : { mb: 'm' }), { children: [(0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ variant: "b1m", color: "gray.2" }, { children: t(`${item.label}`) }), void 0), item.link ? ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Link, Object.assign({ id: `confirm_modal_item_link_${itemIndex}`, href: item.link }, { children: formattedValue }), void 0)) : ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ variant: "b1m", color: "highlightText" }, { children: formattedValue || '[None]' }), void 0))] }), void 0), ((!isLastItem && item.hr !== false) || item.hr) && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Hr, { color: "gray.4" }, void 0))] }, itemIndex));
    };
    const renderSectionItems = (items) => {
        return items.map((item, index) => renderItem(item, index, index + 1 === items.length));
    };
    const renderSections = (sections) => sections.map((section, index) => ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [section.label && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, { children: (0, jsx_runtime_1.jsx)(polymesh_ui_1.Heading, Object.assign({ variant: "h5", mb: "m", mt: "4" }, { children: t(`${section.label}`) }), void 0) }, void 0)), renderSectionItems(section.items)] }, `section${index.toString()}`)));
    const onCancel = () => {
        setConfirmationStatus(definition_1.ConfirmationStatus.None);
        if (inFlight)
            dispatch(appStateActions.setAsync(false));
    };
    return ((0, jsx_runtime_1.jsxs)(polymesh_ui_1.Modal, Object.assign({ isCloseable: false, isOpen: confirmationStatus === definition_1.ConfirmationStatus.Pending, maxWidthContainer: 750 }, { children: [(0, jsx_runtime_1.jsxs)(polymesh_ui_1.Modal.Body, Object.assign({ width: 656 }, { children: [(0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, { children: (0, jsx_runtime_1.jsx)(polymesh_ui_1.Heading, Object.assign({ variant: "h5" }, { children: t(`${confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.title}`, confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.titleArgs) }), void 0) }, void 0), (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.message) && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, { children: (0, jsx_runtime_1.jsx)(polymesh_ui_1.Paragraph, Object.assign({ mt: 20 }, { children: t(`${confirmationData.message}`, confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.messageArgs) }), void 0) }, void 0)), (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.body) && (0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, Object.assign({ mt: "m" }, { children: confirmationData.body }), void 0), (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.sections) && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, Object.assign({ mt: "l" }, { children: renderSections(confirmationData.sections) }), void 0)), (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.footer) && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, Object.assign({ mt: "m" }, { children: confirmationData.footer }), void 0))] }), void 0), (0, jsx_runtime_1.jsx)(polymesh_ui_1.Modal.Footer, { children: (0, jsx_runtime_1.jsxs)(polymesh_ui_1.Flex, Object.assign({ justifyContent: hasFees ? 'space-between' : 'flex-end' }, { children: [hasFees && ((0, jsx_runtime_1.jsxs)(polymesh_ui_1.Flex, Object.assign({ flexDirection: "column", alignItems: "flex-start" }, { children: [(0, jsx_runtime_1.jsxs)(polymesh_ui_1.Flex, Object.assign({ flex: 1, flexDirection: "row", justifyContent: "space-between", mt: "1" }, { children: [(0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, { children: (0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ variant: "b3m", color: "gray.2" }, { children: "Total cost" }), void 0) }, void 0), (0, jsx_runtime_1.jsx)(polymesh_ui_1.Box, Object.assign({ mb: 1, ml: "s" }, { children: (0, jsx_runtime_1.jsx)(polymesh_ui_1.TooltipIcon, { content: "This will be withdrawn from your wallet balance.", iconButtonProps: {
                                                    buttonProps: {
                                                        onMouseEnter: heap.hover({
                                                            id: 'confirm_modal_cost_tooltip',
                                                        }),
                                                    },
                                                } }, void 0) }), void 0)] }), void 0), (0, jsx_runtime_1.jsxs)(polymesh_ui_1.Box, { children: [(0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ variant: "b2m", color: "gray.1" }, { children: formatters.formatAmount(protocolFees || new polymesh_sdk_1.BigNumber(0)) }), void 0), (0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ variant: "b2m", color: "gray.2" }, { children: ` ${tokenSymbol}` }), void 0)] }, void 0)] }), void 0)), !enoughBalance && ((0, jsx_runtime_1.jsx)(polymesh_ui_1.Text, Object.assign({ color: "alert", fontSize: "0", fontWeight: "bold", width: "15%", mr: "m" }, { children: "Insufficent funds available" }), void 0)), (0, jsx_runtime_1.jsxs)(polymesh_ui_1.Box, { children: [(0, jsx_runtime_1.jsx)(polymesh_ui_1.ButtonLarge, Object.assign({ id: `${signingPackageId}_confirm_modal_cancel_button`, variant: "secondary", onClick: onCancel }, { children: t('General:cancel') }), void 0), (0, jsx_runtime_1.jsx)(polymesh_ui_1.ButtonLarge, Object.assign({ id: `${signingPackageId}_confirm_modal_confirm_button`, disabled: !enoughBalance, onClick: () => setConfirmationStatus(definition_1.ConfirmationStatus.Done) }, { children: (confirmationData === null || confirmationData === void 0 ? void 0 : confirmationData.submitButtonTitle) || t('General:confirm') }), void 0)] }, void 0)] }), void 0) }, void 0)] }), void 0));
};
exports.TxConfirmModal = TxConfirmModal;
//# sourceMappingURL=TxConfirmModal.js.map