"use strict";
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const types_1 = require("../../types");
const util_1 = require("@polkadot/util");
const util_crypto_1 = require("@polkadot/util-crypto");
const util_2 = require("../util");
function retrieve(api, address) {
    try {
        // yes, this can fail, don't care too much, catch will catch it
        const decoded = util_1.isU8a(address)
            ? address
            : util_crypto_1.decodeAddress((address || '').toString());
        if (decoded.length === 32) {
            const accountId = types_1.createType(api.registry, 'AccountId', decoded);
            return api.derive.accounts.idToIndex(accountId).pipe(operators_1.map((accountIndex) => [accountId, accountIndex]));
        }
        const accountIndex = types_1.createType(api.registry, 'AccountIndex', decoded);
        return api.derive.accounts.indexToId(accountIndex).pipe(operators_1.map((accountId) => [accountId, accountIndex]));
    }
    catch (error) {
        return rxjs_1.of([undefined, undefined]);
    }
}
/**
 * @name idAndIndex
 * @param {(Address | AccountId | AccountIndex | string | null)} address - An accounts address in various formats.
 * @description  An array containing the [[AccountId]] and [[AccountIndex]] as optional values.
 * @example
 * <BR>
 *
 * ```javascript
 * api.derive.accounts.idAndIndex('F7Hs', ([id, ix]) => {
 *   console.log(`AccountId #${id} with corresponding AccountIndex ${ix}`);
 * });
 * ```
 */
function idAndIndex(api) {
    return util_2.memo((address) => retrieve(api, address));
}
exports.idAndIndex = idAndIndex;
