"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAptosStakingPositionsQuerySelector = exports.useAptosMappedStakingPositions = exports.useAptosValidators = exports.useAptosPreloadData = void 0;
const react_1 = require("react");
const preload_data_1 = require("@ledgerhq/coin-aptos/preload-data");
const observable_1 = require("../../observable");
const account_1 = require("../../account");
const staking_1 = require("./staking");
function useAptosPreloadData(currency) {
    return (0, observable_1.useObservable)((0, preload_data_1.getAptosPreloadData)(currency), (0, preload_data_1.getCurrentAptosPreloadData)(currency));
}
exports.useAptosPreloadData = useAptosPreloadData;
function useAptosValidators(currency, search) {
    const data = useAptosPreloadData(currency);
    return (0, react_1.useMemo)(() => {
        const validators = data?.validators ?? [];
        if (validators.length === 0 || !search || search === "") {
            return validators;
        }
        const lowercaseSearch = search.toLowerCase();
        const filtered = validators.filter(validator => validator.name?.toLowerCase().includes(lowercaseSearch) ||
            validator.address.toLowerCase().includes(lowercaseSearch));
        const flags = [];
        const output = [];
        for (let i = 0; i < filtered.length; i++) {
            if (flags[filtered[i].address])
                continue;
            flags[filtered[i].address] = true;
            output.push(filtered[i]);
        }
        return output;
    }, [data, search]);
}
exports.useAptosValidators = useAptosValidators;
function useAptosMappedStakingPositions(account) {
    const validators = useAptosValidators(account.currency, "");
    const stakingPositions = account.aptosResources?.stakingPositions;
    const unit = (0, account_1.getAccountCurrency)(account).units[0];
    return (0, react_1.useMemo)(() => {
        const mappedStakingPositions = (0, staking_1.mapStakingPositions)(stakingPositions || [], validators, unit);
        return mappedStakingPositions;
    }, [stakingPositions, validators, unit]);
}
exports.useAptosMappedStakingPositions = useAptosMappedStakingPositions;
function useAptosStakingPositionsQuerySelector(account, transaction) {
    const stakingPositions = useAptosMappedStakingPositions(account);
    const options = (0, react_1.useMemo)(() => stakingPositions.filter(sp => transaction.mode === "unstake" ? sp.active.gt(0) : sp.inactive.gt(0)), [stakingPositions, transaction]);
    const selectedValidatorAddress = transaction.recipient;
    const value = (0, react_1.useMemo)(() => stakingPositions.find(({ validatorId }) => validatorId === selectedValidatorAddress), [stakingPositions, selectedValidatorAddress]);
    return {
        options,
        value,
    };
}
exports.useAptosStakingPositionsQuerySelector = useAptosStakingPositionsQuerySelector;
//# sourceMappingURL=react.js.map