"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLedgerFirstShuffledValidatorsCosmosFamily = exports.useSortedValidators = exports.useCosmosFamilyDelegationsQuerySelector = exports.useCosmosFamilyMappedDelegations = exports.useCosmosFamilyPreloadData = void 0;
const invariant_1 = __importDefault(require("invariant"));
const react_1 = require("react");
const chain_1 = __importDefault(require("@ledgerhq/coin-cosmos/chain/chain"));
const preloadedData_1 = require("@ledgerhq/coin-cosmos/preloadedData");
const account_1 = require("../../account");
const useMemoOnce_1 = __importDefault(require("../../hooks/useMemoOnce"));
const logic_1 = require("./logic");
function useCosmosFamilyPreloadData(currencyId) {
    const getCurrent = preloadedData_1.getCurrentCosmosPreloadData;
    const getUpdates = preloadedData_1.getCosmosPreloadDataUpdates;
    const [state, setState] = (0, react_1.useState)(getCurrent);
    (0, react_1.useEffect)(() => {
        const sub = getUpdates().subscribe(setState);
        return () => sub.unsubscribe();
    }, [getCurrent, getUpdates]);
    return currencyId
        ? state[currencyId] ?? {
            validators: [], // NB initial state because UI need to work even if it's currently "loading", typically after clear cache
        }
        : {
            validators: [], // NB initial state because UI need to work even if it's currently "loading", typically after clear cache
        };
}
exports.useCosmosFamilyPreloadData = useCosmosFamilyPreloadData;
function useCosmosFamilyMappedDelegations(account, mode) {
    const currencyId = account.currency.id;
    const { validators } = useCosmosFamilyPreloadData(currencyId);
    const delegations = account.cosmosResources?.delegations;
    (0, invariant_1.default)(delegations, "cosmos: delegations is required");
    const unit = (0, account_1.getAccountCurrency)(account).units[0];
    return (0, react_1.useMemo)(() => {
        const mappedDelegations = (0, logic_1.mapDelegations)(delegations || [], validators, unit);
        return mode === "claimReward"
            ? mappedDelegations.filter(({ pendingRewards }) => pendingRewards.gt(0))
            : mappedDelegations;
    }, [delegations, validators, mode, unit]);
}
exports.useCosmosFamilyMappedDelegations = useCosmosFamilyMappedDelegations;
function useCosmosFamilyDelegationsQuerySelector(account, transaction, delegationSearchFilter = logic_1.searchFilter) {
    const [query, setQuery] = (0, react_1.useState)("");
    const delegations = useCosmosFamilyMappedDelegations(account, transaction.mode);
    const options = (0, react_1.useMemo)(() => delegations.filter(delegationSearchFilter(query)), [query, delegations, delegationSearchFilter]);
    const selectedValidator = transaction.validators && transaction.validators[0];
    const value = (0, react_1.useMemo)(() => {
        switch (transaction.mode) {
            case "redelegate":
                (0, invariant_1.default)(transaction.sourceValidator, "cosmos: sourceValidator is required");
                return options.find(({ validatorAddress }) => validatorAddress === transaction.sourceValidator);
            default:
                return (selectedValidator &&
                    delegations.find(({ validatorAddress }) => validatorAddress === selectedValidator.address));
        }
    }, [delegations, selectedValidator, transaction, options]);
    return {
        query,
        setQuery,
        options,
        value,
    };
}
exports.useCosmosFamilyDelegationsQuerySelector = useCosmosFamilyDelegationsQuerySelector;
/** Hook to search and sort SR list according to initial votes and query */
function useSortedValidators(search, validators, delegations, validatorSearchFilter = logic_1.searchFilter) {
    const initialVotes = (0, useMemoOnce_1.default)(() => delegations.map(({ address }) => address));
    const mappedValidators = (0, react_1.useMemo)(() => validators.map((validator, rank) => ({
        rank: rank + 1,
        validator,
    })), [validators]);
    const sortedVotes = (0, react_1.useMemo)(() => mappedValidators
        .filter(({ validator }) => initialVotes.includes(validator.validatorAddress))
        .concat(mappedValidators.filter(({ validator }) => !initialVotes.includes(validator.validatorAddress))), [mappedValidators, initialVotes]);
    const sr = (0, react_1.useMemo)(() => (search ? mappedValidators.filter(validatorSearchFilter(search)) : sortedVotes), [search, mappedValidators, sortedVotes, validatorSearchFilter]);
    return sr;
}
exports.useSortedValidators = useSortedValidators;
function useLedgerFirstShuffledValidatorsCosmosFamily(currencyId, searchInput) {
    const data = (0, preloadedData_1.getCurrentCosmosPreloadData)()[currencyId];
    const ledgerValidatorAddress = (0, chain_1.default)(currencyId).ledgerValidator;
    return (0, react_1.useMemo)(() => {
        return reorderValidators(data?.validators ?? [], ledgerValidatorAddress, searchInput);
    }, [data, ledgerValidatorAddress, searchInput]);
}
exports.useLedgerFirstShuffledValidatorsCosmosFamily = useLedgerFirstShuffledValidatorsCosmosFamily;
function reorderValidators(validators, ledgerValidatorAddress, searchInput) {
    const sortedValidators = validators
        .filter(validator => validator.commission !== 1.0)
        .filter(validator => searchInput ? validator.name.toLowerCase().includes(searchInput.toLowerCase()) : true)
        .sort((a, b) => b.tokens - a.tokens);
    // move Ledger validator to the first position
    if (ledgerValidatorAddress) {
        const ledgerValidator = sortedValidators.find(v => v.validatorAddress === ledgerValidatorAddress);
        if (ledgerValidator) {
            const sortedValidatorsLedgerFirst = sortedValidators.filter(v => v.validatorAddress !== ledgerValidatorAddress);
            sortedValidatorsLedgerFirst.unshift(ledgerValidator);
            return sortedValidatorsLedgerFirst;
        }
    }
    return sortedValidators;
}
//# sourceMappingURL=react.js.map