"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useStakingPositions = exports.useRandomBaker = exports.useBaker = exports.useDelegation = exports.useBakers = void 0;
const react_1 = require("react");
const index_1 = require("@ledgerhq/coin-tezos/network/index");
function useBakers(whitelistAddresses) {
    const [whitelistedBakers, setWhitelistedBakers] = (0, react_1.useState)(() => index_1.bakers.listBakersWithDefault(whitelistAddresses));
    (0, react_1.useEffect)(() => {
        index_1.bakers.listBakers(whitelistAddresses).then(setWhitelistedBakers);
    }, [index_1.bakers, whitelistAddresses]);
    return whitelistedBakers;
}
exports.useBakers = useBakers;
function useDelegation(account) {
    const [delegation, setDelegation] = (0, react_1.useState)(() => index_1.bakers.getAccountDelegationSync(account));
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        index_1.bakers.loadAccountDelegation(account).then(delegation => {
            if (cancelled)
                return;
            setDelegation(delegation);
        });
        return () => {
            cancelled = true;
        };
    }, [account]);
    return delegation;
}
exports.useDelegation = useDelegation;
function useBaker(addr) {
    const [baker, setBaker] = (0, react_1.useState)(() => index_1.bakers.getBakerSync(addr));
    index_1.bakers.loadBaker(addr).then(setBaker);
    return baker;
}
exports.useBaker = useBaker;
//  select a random baker for the mount time (assuming bakers length don't change)
function useRandomBaker(bakers) {
    const randomBakerIndex = (0, react_1.useMemo)(() => {
        const nonFullBakers = bakers.filter(b => b.capacityStatus !== "full");
        if (nonFullBakers.length > 0) {
            // if there are non full bakers, we pick one
            const i = Math.floor(Math.random() * nonFullBakers.length);
            return bakers.indexOf(nonFullBakers[i]);
        }
        // fallback on random between only full bakers
        return Math.floor(Math.random() * bakers.length); // for perf, we only want to re-calc on bakers.length changes
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [bakers.length]);
    return bakers[randomBakerIndex];
}
exports.useRandomBaker = useRandomBaker;
function useStakingPositions(account) {
    const delegation = useDelegation(account);
    return (0, react_1.useMemo)(() => {
        if (account.type !== "Account" || !delegation?.address)
            return [];
        return [
            {
                uid: account.freshAddress,
                address: account.freshAddress,
                delegate: delegation.address,
                state: "active",
                asset: { type: "native" },
                amount: BigInt(account.balance.toString()),
            },
        ];
    }, [account, delegation]);
}
exports.useStakingPositions = useStakingPositions;
//# sourceMappingURL=react.js.map