"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSearchValidators = exports.useMultiversXRandomizedValidators = exports.useMultiversXPreloadData = void 0;
const bignumber_js_1 = require("bignumber.js");
const react_1 = require("react");
const preload_1 = require("@ledgerhq/coin-multiversx/preload");
const randomizeProviders_1 = require("@ledgerhq/coin-multiversx/helpers/randomizeProviders");
const constants_1 = require("./constants");
function useMultiversXPreloadData() {
    const [state, setState] = (0, react_1.useState)(preload_1.getCurrentMultiversXPreloadData);
    (0, react_1.useEffect)(() => {
        const sub = (0, preload_1.getMultiversXPreloadDataUpdates)().subscribe(data => {
            setState(data);
        });
        return () => sub.unsubscribe();
    }, []);
    return state;
}
exports.useMultiversXPreloadData = useMultiversXPreloadData;
function useMultiversXRandomizedValidators() {
    const { validators } = useMultiversXPreloadData();
    return (0, react_1.useMemo)(() => (0, randomizeProviders_1.randomizeProviders)(validators), [validators]);
}
exports.useMultiversXRandomizedValidators = useMultiversXRandomizedValidators;
function useSearchValidators(validators, search) {
    return (0, react_1.useMemo)(() => {
        const needle = search.toLowerCase();
        // Filter the providers such that they'll match the possible search criteria.
        const filter = (validator) => {
            const [foundByContract, foundByName] = [
                validator.contract.toLowerCase().includes(needle),
                validator.identity.name ? validator.identity.name.toLowerCase().includes(needle) : false,
            ];
            return foundByName || foundByContract;
        };
        // Map the providers such that they'll be assigned the "disabled" key if conditions are met.
        const disable = (validator) => {
            const [alpha, beta] = [validator.maxDelegationCap, validator.totalActiveStake];
            const delegative = alpha !== "0" && validator.withDelegationCap;
            const difference = new bignumber_js_1.BigNumber(alpha).minus(beta);
            return Object.assign(validator, {
                disabled: delegative && difference.isLessThan(constants_1.MIN_DELEGATION_AMOUNT),
            });
        };
        // Sort the providers such that Figment by Ledger will always be first.
        const sort = (validator) => validator.contract === constants_1.MULTIVERSX_LEDGER_VALIDATOR_ADDRESS ? -1 : 1;
        const items = validators.sort(sort).map(disable);
        return search ? items.filter(filter) : items;
    }, [validators, search]);
}
exports.useSearchValidators = useSearchValidators;
//# sourceMappingURL=react.js.map