"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @jest-environment jsdom
 */
const invariant_1 = __importDefault(require("invariant"));
const chain_1 = __importDefault(require("@ledgerhq/coin-cosmos/chain/chain"));
const preloadedData_1 = require("@ledgerhq/coin-cosmos/preloadedData");
const preloadedData_mock_1 = __importDefault(require("@ledgerhq/coin-cosmos/preloadedData.mock"));
const LiveConfig_1 = require("@ledgerhq/live-config/LiveConfig");
const live_env_1 = require("@ledgerhq/live-env");
const react_1 = require("@testing-library/react");
require("../../__tests__/test-helpers/dom-polyfill");
const account_1 = require("../../account");
const bridge_1 = require("../../bridge");
const cache_1 = require("../../bridge/cache");
const sharedConfig_1 = require("../../config/sharedConfig");
const currencies_1 = require("../../currencies");
const account_2 = require("../../mock/account");
const hooks = __importStar(require("./react"));
const localCache = {};
const cache = (0, cache_1.makeBridgeCacheSystem)({
    saveData(c, d) {
        localCache[c.id] = d;
        return Promise.resolve();
    },
    getData(c) {
        return Promise.resolve(localCache[c.id]);
    },
});
describe("cosmos/react", () => {
    beforeAll(() => {
        LiveConfig_1.LiveConfig.setConfig(sharedConfig_1.liveConfig);
        const cosmos = (0, chain_1.default)("cosmos");
        cosmos.lcd = LiveConfig_1.LiveConfig.getValueByKey("config_currency_cosmos").lcd;
        cosmos.minGasPrice = LiveConfig_1.LiveConfig.getValueByKey("config_currency_cosmos").minGasPrice;
        cosmos.ledgerValidator = LiveConfig_1.LiveConfig.getValueByKey("config_currency_cosmos").ledgerValidator;
    });
    describe("useCosmosFamilyPreloadData", () => {
        it("should return Cosmos preload data and updates", async () => {
            const { prepare } = setup();
            await (0, react_1.act)(() => prepare());
            const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyPreloadData("cosmos"));
            const data = (0, preloadedData_1.getCurrentCosmosPreloadData)()["cosmos"];
            expect(result.current).toStrictEqual(data);
            expect(result.current).toStrictEqual(preloadedData_mock_1.default);
        });
    });
    describe("useCosmosFormattedDelegations", () => {
        it("should return formatted delegations", async () => {
            const { account, prepare } = setup();
            await prepare();
            const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyMappedDelegations(account));
            const delegations = account.cosmosResources?.delegations;
            (0, invariant_1.default)(delegations, "cosmos: delegations is required");
            expect(account.cosmosResources?.delegations?.some(d => d.amount[0] === 0)).toBe(false);
            expect(Array.isArray(result.current)).toBe(true);
            expect(result.current.length).toBe(delegations.length);
            const { code } = (0, account_1.getAccountCurrency)(account).units[0];
            expect(result.current[0].formattedAmount.split(" ")[1]).toBe(code);
            expect(result.current[0].formattedPendingRewards.split(" ")[1]).toBe(code);
            expect(typeof result.current[0].rank).toBe("number");
            expect(result.current[0].validator.validatorAddress).toBe(delegations[0].validatorAddress);
        });
        describe("mode: claimReward", () => {
            it("should only return delegations which have some pending rewards", async () => {
                const { account, prepare } = setup();
                await prepare();
                const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyMappedDelegations(account, "claimReward"));
                expect(result.current.length).toBe(3);
            });
        });
    });
    describe("useCosmosFamilyDelegationsQuerySelector", () => {
        it("should return delegations filtered by query as options", async () => {
            const { account, transaction, prepare } = setup();
            await prepare();
            (0, invariant_1.default)(account.cosmosResources, "cosmos: account and cosmos resources required");
            if (!account.cosmosResources)
                throw new Error("cosmos: account and cosmos resources required");
            const delegations = account.cosmosResources.delegations || [];
            const newTx = {
                ...transaction,
                mode: "delegate",
                validators: delegations.map(({ validatorAddress, amount }) => ({
                    address: validatorAddress,
                    amount,
                })),
            };
            const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyDelegationsQuerySelector(account, newTx));
            expect(result.current.options.length).toBe(delegations.length);
            (0, react_1.act)(() => {
                result.current.setQuery("FRESHATOMS");
            });
            expect(result.current.options.length).toBe(0);
        });
        it("should return the first delegation as value", async () => {
            const { account, transaction, prepare } = setup();
            await prepare();
            (0, invariant_1.default)(account.cosmosResources, "cosmos: account and cosmos resources required");
            const delegations = account.cosmosResources.delegations || [];
            const newTx = {
                ...transaction,
                mode: "delegate",
                validators: delegations.map(({ validatorAddress, amount }) => ({
                    address: validatorAddress,
                    amount,
                })),
            };
            const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyDelegationsQuerySelector(account, newTx));
            expect(result.current.value.validator
                .validatorAddress).toBe(delegations[0].validatorAddress);
        });
        it("should find delegation by sourceValidator field and return as value for redelegate", async () => {
            const { account, transaction, prepare } = setup();
            await prepare();
            (0, invariant_1.default)(account.cosmosResources, "cosmos: account and cosmos resources required");
            const delegations = account.cosmosResources.delegations || [];
            const sourceValidator = delegations[delegations.length - 1].validatorAddress;
            const newTx = {
                ...transaction,
                mode: "redelegate",
                validators: delegations.map(({ validatorAddress, amount }) => ({
                    address: validatorAddress,
                    amount,
                })),
                sourceValidator,
            };
            const { result } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyDelegationsQuerySelector(account, newTx));
            expect(result.current.value.validator
                .validatorAddress).toBe(sourceValidator);
        });
    });
    describe("useSortedValidators", () => {
        it("should reutrn sorted validators", async () => {
            const { account, prepare } = setup();
            await prepare();
            const { result: preloadDataResult } = (0, react_1.renderHook)(() => hooks.useCosmosFamilyPreloadData("cosmos"));
            const { validators } = preloadDataResult.current;
            const delegations = (account.cosmosResources?.delegations || []).map(({ validatorAddress, amount }) => ({
                address: validatorAddress,
                amount,
            }));
            const { result } = (0, react_1.renderHook)(() => hooks.useSortedValidators("", validators, delegations));
            expect(result.current.length).toBe(validators.length);
            const { result: searchResult } = (0, react_1.renderHook)(() => hooks.useSortedValidators("Nodeasy.com", validators, delegations));
            expect(searchResult.current.length).toBe(1);
        });
    });
    describe("reorderValidators", () => {
        it("should return a list of Validators with Ledger first", () => {
            const { result } = (0, react_1.renderHook)(() => hooks.useLedgerFirstShuffledValidatorsCosmosFamily("cosmos"));
            const LEDGER_VALIDATOR_ADDRESS = (0, chain_1.default)("cosmos").ledgerValidator;
            expect(result.current[0].validatorAddress).toBe(LEDGER_VALIDATOR_ADDRESS);
        });
    });
});
function setup() {
    (0, live_env_1.setEnv)("MOCK", "1");
    (0, live_env_1.setEnv)("EXPERIMENTAL_CURRENCIES", "cosmos");
    const seed = "cosmos-2";
    const currency = (0, currencies_1.getCryptoCurrencyById)("cosmos");
    const a = (0, account_2.genAccount)(seed, {
        currency,
    });
    const account = (0, account_2.genAddingOperationsInAccount)(a, 3, seed);
    const currencyBridge = (0, bridge_1.getCurrencyBridge)(currency);
    const bridge = (0, bridge_1.getAccountBridge)(account);
    const transaction = bridge.createTransaction(account);
    return {
        account,
        currencyBridge,
        transaction,
        prepare: async () => cache.prepareCurrency(currency),
    };
}
//# sourceMappingURL=react.test.js.map