"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 parseResult(_api, { allIds, allProposals, approvalIds, proposalCount }) {
    const approvals = [];
    const proposals = [];
    allIds.forEach((id, index) => {
        if (allProposals[index].isSome) {
            const isApproval = approvalIds.some((approvalId) => approvalId.eq(id));
            const derived = { id, proposal: allProposals[index].unwrap() };
            if (isApproval) {
                approvals.push(derived);
            }
            else {
                proposals.push(derived);
            }
        }
    });
    return { approvals, proposalCount, proposals };
}
function retrieveProposals(api, proposalCount, approvalIds) {
    const proposalIds = [];
    const count = proposalCount.toNumber();
    for (let index = 0; index < count; index++) {
        const isApproval = approvalIds.some((id) => id.eqn(index));
        if (!isApproval) {
            proposalIds.push(types_1.createType(api.registry, 'ProposalIndex', index));
        }
    }
    const allIds = [...proposalIds, ...approvalIds];
    return rxjs_1.combineLatest([
        api.query.treasury.proposals.multi(allIds)
    ]).pipe(operators_1.map(([allProposals]) => parseResult(api, { allIds, allProposals, approvalIds, proposalCount })));
}
/**
 * @description Retrieve all active and approved treasury proposals, along with their info
 */
function proposals(api) {
    return util_1.memo(() => api.query.treasury
        ? rxjs_1.combineLatest([
            api.query.treasury.proposalCount(),
            api.query.treasury.approvals()
        ]).pipe(operators_1.switchMap(([proposalCount, approvalIds]) => retrieveProposals(api, proposalCount, approvalIds)))
        : rxjs_1.of({
            approvals: [],
            proposalCount: types_1.createType(api.registry, 'ProposalIndex'),
            proposals: []
        }));
}
exports.proposals = proposals;
