"use strict";
/*
 *
 * Copyright 2018-present NEM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultisigService = void 0;
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
class MultisigService {
    /**
     * Creates an instance of MultisigService.
     * @param {Profile} profile
     */
    constructor(profile) {
        this.profile = profile;
        this.multisigHttp = this.profile.repositoryFactory.createMultisigRepository();
    }
    /**
     * Gets self and children multisig accounts addresses from the network
     * @public
     * @returns {Observable<Address[]>}
     */
    getSelfAndChildrenAddresses() {
        return this.multisigHttp.getMultisigAccountGraphInfo(this.profile.address).pipe((0, operators_1.switchMap)((graphInfo) => this.getAddressesFromGraphInfo(graphInfo)), (0, operators_1.catchError)((ignored) => (0, rxjs_1.of)([this.profile.address])));
    }
    /**
     * Gets children multisig accounts nultisig info from the network
     * @returns {Promise<MultisigAccountInfo[]>}
     */
    getChildrenMultisigAccountInfo() {
        return this.multisigHttp
            .getMultisigAccountGraphInfo(this.profile.address)
            .pipe((0, operators_1.switchMap)((graphInfo) => this.multisigInfoFromGraphInfo(graphInfo)), (0, operators_1.toArray)(), (0, operators_1.catchError)((ignored) => (0, rxjs_1.of)(null)))
            .toPromise();
    }
    /**
     * Gets self and children multisig accounts addresses from a MultisigAccountGraphInfo
     * @private
     * @param {MultisigAccountGraphInfo} graphInfo
     * @returns {Observable<Address[]>}
     */
    getAddressesFromGraphInfo(graphInfo) {
        return this.multisigInfoFromGraphInfo(graphInfo).pipe((0, operators_1.map)(({ accountAddress }) => accountAddress), (0, operators_1.toArray)());
    }
    multisigInfoFromGraphInfo(graphInfo) {
        const { multisigEntries } = graphInfo;
        return (0, rxjs_1.from)([...multisigEntries.keys()].sort((a, b) => b - a)).pipe((0, operators_1.map)((key) => multisigEntries.get(key) || []), (0, operators_1.filter)((x) => x.length > 0), (0, operators_1.flatMap)((multisigAccountInfo) => multisigAccountInfo));
    }
}
exports.MultisigService = MultisigService;
