"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.
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const accounts = __importStar(require("./accounts"));
const chain = __importStar(require("./chain"));
const contracts = __importStar(require("./contracts"));
const imOnline = __importStar(require("./imOnline"));
const session = __importStar(require("./session"));
const staking = __importStar(require("./staking"));
const treasury = __importStar(require("./treasury"));
__export(require("./type"));
exports.derive = { accounts, chain, contracts, imOnline, session, staking, treasury };
// Enable derive only if some of these modules are available
const deriveAvail = {
    contracts: ['contracts'],
    council: ['council'],
    democracy: ['democracy'],
    elections: ['electionsPhragmen', 'elections'],
    imOnline: ['imOnline'],
    session: ['session'],
    society: ['society'],
    staking: ['staking'],
    technicalCommittee: ['technicalCommittee'],
    treasury: ['treasury']
};
/**
 * Returns an object that will inject `api` into all the functions inside
 * `allSections`, and keep the object architecture of `allSections`.
 */
/** @internal */
function injectFunctions(api, allSections) {
    const queryKeys = Object.keys(api.query);
    return Object
        .keys(allSections)
        .filter((sectionName) => !deriveAvail[sectionName] || deriveAvail[sectionName].some((query) => queryKeys.includes(query)))
        .reduce((deriveAcc, sectionName) => {
        const section = allSections[sectionName];
        deriveAcc[sectionName] = Object
            .keys(section)
            .reduce((sectionAcc, _methodName) => {
            const methodName = _methodName;
            // Not sure what to do here, casting as any. Though the final types are good
            const method = section[methodName](api);
            // idem
            sectionAcc[methodName] = method;
            return sectionAcc;
        }, {});
        return deriveAcc;
    }, {});
}
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
/** @internal */
function decorateDerive(api, custom = {}) {
    return Object.assign(Object.assign({}, injectFunctions(api, exports.derive)), injectFunctions(api, custom));
}
exports.default = decorateDerive;
