"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("../util");
function unwrapSessionIds(stashId, queuedKeys, nextKeys) {
    const sessionIds = (queuedKeys.find(([currentId]) => currentId.eq(stashId)) || [undefined, []])[1];
    const nextSessionIds = nextKeys.unwrapOr([]);
    return {
        nextSessionIds,
        sessionIds
    };
}
function retrieve(api, stashId) {
    return rxjs_1.combineLatest([
        api.query.session.queuedKeys(),
        api.queryMulti([
            [api.query.staking.bonded, stashId],
            [api.query.staking.nominators, stashId],
            [api.query.staking.payee, stashId],
            [api.query.staking.stakers, stashId],
            [api.query.staking.validators, stashId],
            [api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
        ])
    ]);
}
/**
 * @description From a stash, retrieve the controllerId and all relevant details
 */
function query(api) {
    return util_1.memo((accountId) => {
        const stashId = types_1.createType(api.registry, 'AccountId', accountId);
        return retrieve(api, stashId).pipe(operators_1.switchMap(([queuedKeys, [controllerIdOpt, nominatorsOpt, rewardDestination, stakers, [validatorPrefs], nextKeys]]) => {
            const controllerId = controllerIdOpt.unwrapOr(null);
            return controllerId
                ? api.query.staking.ledger(controllerId).pipe(operators_1.map((stakingLedgerOpt) => (Object.assign({ accountId: stashId, controllerId, nominators: nominatorsOpt.unwrapOr([{ targets: [] }])[0].targets, rewardDestination,
                    stakers, stakingLedger: stakingLedgerOpt.unwrapOr(undefined), stashId,
                    validatorPrefs }, unwrapSessionIds(stashId, queuedKeys, nextKeys)))))
                : rxjs_1.of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
        }));
    });
}
exports.query = query;
