"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 AccountIndex_1 = require("../../types/primitive/Generic/AccountIndex");
const types_1 = require("../../types");
const util_1 = require("../util");
const enumsetSize = AccountIndex_1.ENUMSET_SIZE.toNumber();
/**
 * @name indexes
 * @returns Returns all the indexes on the system.
 * @description This is an unwieldly query since it loops through
 * all of the enumsets and returns all of the values found. This could be up to 32k depending
 * on the number of active accounts in the system
 * @example
 * <BR>
 *
 * ```javascript
 * api.derive.accounts.indexes((indexes) => {
 *   console.log('All existing AccountIndexes', indexes);
 * });
 * ```
 */
function indexes(api) {
    return util_1.memo(() => (api.query.indices.nextEnumSet
        ? api.query.indices.nextEnumSet().pipe(
        // use the nextEnumSet (which is a counter of the number of sets) to construct
        // a range of values to query [0, 1, 2, ...]. Retrieve the full enum set for the
        // specific index - each query can return up to ENUMSET_SIZE (64) records, each
        // containing an AccountId
        operators_1.switchMap((next) => api.query.indices.enumSet.multi([...Array(next.toNumber() + 1).keys()])))
        : rxjs_1.of([])).pipe(operators_1.map((all) => all.reduce((result, list, outerIndex) => {
        (list || []).forEach((accountId, innerIndex) => {
            // re-create the index based on position 0 is [0][0] and likewise
            // 64 (0..63 in first) is [1][0] (the first index value in set 2)
            const index = (outerIndex * enumsetSize) + innerIndex;
            result[accountId.toString()] = types_1.createType(api.registry, 'AccountIndex', index);
        });
        return result;
    }, {}))));
}
exports.indexes = indexes;
