"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAccountBannerState = void 0;
const chain_1 = __importDefault(require("@ledgerhq/coin-cosmos/chain/chain"));
const preloadedData_1 = require("@ledgerhq/coin-cosmos/preloadedData");
const logic_1 = require("./logic");
function getAccountBannerState(account) {
    // Group current validator
    const cosmosResources = account.cosmosResources
        ? account.cosmosResources
        : { delegations: [], redelegations: [] };
    const delegationAddresses = cosmosResources.delegations.map(delegation => {
        return delegation.validatorAddress;
    });
    const redelegationAddresses = cosmosResources.redelegations.map(redelegation => {
        return redelegation.validatorDstAddress;
    });
    const validatorAdresses = [...delegationAddresses, ...redelegationAddresses];
    const LEDGER_VALIDATOR_ADDRESS = (0, chain_1.default)(account.currency.id).ledgerValidator;
    // Get ledger validator data
    const { validators } = (0, preloadedData_1.getCurrentCosmosPreloadData)()[account.currency.id] ?? {
        validators: [],
    };
    const ledgerValidator = validators.find(validator => validator.validatorAddress === LEDGER_VALIDATOR_ADDRESS);
    // if Ledger doesn't provide validator, we don't display banner
    if (!ledgerValidator) {
        return {
            display: false,
            redelegate: false,
            validatorSrcAddress: "",
            ledgerValidator,
        };
    }
    // Find user current worst validator (default validator is ledger)
    let worstValidator = ledgerValidator;
    for (let i = 0; i < validatorAdresses.length; i++) {
        const validatorAdress = validatorAdresses[i];
        const validator = validators.find(validator => validator.validatorAddress === validatorAdress);
        if (validator &&
            worstValidator.commission < validator.commission &&
            (0, logic_1.canRedelegate)(account, validator)) {
            worstValidator = validator;
        }
    }
    let redelegate = false;
    let validatorSrcAddress = "";
    let display = false;
    if (worstValidator?.validatorAddress === ledgerValidator?.validatorAddress) {
        // Not found worst validator than ledger
        if ((0, logic_1.canDelegate)(account)) {
            // Delegate remaining ATOM (not staked)
            display = true;
        }
    }
    else {
        // Redelegate to the worst validator
        display = true;
        redelegate = true;
        validatorSrcAddress = worstValidator.validatorAddress;
    }
    return {
        display,
        redelegate,
        validatorSrcAddress,
        ledgerValidator,
    };
}
exports.getAccountBannerState = getAccountBannerState;
//# sourceMappingURL=banner.js.map