"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.voterPositions = voterPositions;

var _types = require("@polkadot/types");

var _bn = _interopRequireDefault(require("bn.js"));

var _rxjs = require("rxjs");

var _operators = require("rxjs/operators");

var _drr = require("../util/drr");

// Copyright 2017-2019 @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.

/**
 * @name voterPositions
 * @returns An mapping of all current voter accounts to their voter set and global index.
 * @example
 * <BR>
 *
 * ```javascript
 * api.derive.elections.voterPositions((voters) => {
 *   const { index, setIndex, globalIndex } = voters[ALICE];
 *   console.log(`ALICE is a voter at index ${index} in voter set ${setIndex}, with global index ${globalIndex}.`);
 * });
 * ```
 */
function voterPositions(api) {
  return () => api.query.elections.nextVoterSet().pipe((0, _operators.switchMap)(nextVoterSet => (0, _rxjs.combineLatest)((0, _rxjs.of)(api.consts.elections.voterSetSize), api.query.elections.voters.multi([...Array(+nextVoterSet + 1).keys()].map((_, i) => [i])))), (0, _operators.map)(result => {
    const [setSize, voters] = result;
    return voters.reduce((result, vec, setIndex) => {
      vec.forEach((e, index) => {
        // 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 accountId = e.unwrapOr(null);

        if (accountId) {
          result[accountId.toString()] = {
            globalIndex: setSize.muln(setIndex).addn(index),
            index: new _bn.default(index),
            setIndex: (0, _types.createType)('SetIndex', setIndex)
          };
        }
      });
      return result;
    }, {});
  }), (0, _drr.drr)());
}