import { useCallback, useMemo, useState } from "react";
import { useApi } from "./api";
import { useAccounts } from "./connect";
import { useAsyncEffect } from "../../hooks/async";
import { createSimpleContext } from "../simple";
const saType = [
    "Bailsman",
    "Borrower",
    "Lender",
];
const useSubAccount = ({ useBase }) => {
    const base = useBase();
    const { api } = useApi();
    const { account } = useAccounts();
    const ss58Prefix = useMemo(() => api?._api.registry.chainSS58 ?? 42, [api]);
    const [subAccounts, setSubAccounts] = useState({
        Bailsman: undefined,
        Borrower: undefined,
        Lender: undefined,
    });
    useAsyncEffect(async () => {
        if (api && account) {
            const unsub = await api.query.getAddress.multi(saType.map((t) => [account.address, t]), (res) => {
                setSubAccounts(saType.reduce((total, t, i) => {
                    return { ...total, [t]: res[i].toString() };
                }, {
                    Bailsman: undefined,
                    Borrower: undefined,
                    Lender: undefined,
                }));
            });
            return () => {
                unsub();
            };
        }
    }, [api, account]);
    const getAccount = useCallback((type) => {
        if (!account) {
            return;
        }
        if (!type) {
            return account;
        }
        const address = subAccounts[type];
        if (!address) {
            return;
        }
        const pub = base.utilCrypto?.decodeAddress(address);
        return {
            ...account,
            address: base.utilCrypto?.encodeAddress(pub ?? new Uint8Array(), ss58Prefix) ??
                "",
            pub: Buffer.from(pub ?? []).toString("hex"),
        };
    }, [
        account,
        subAccounts,
        ss58Prefix,
        base.utilCrypto?.decodeAddress,
        base.utilCrypto?.encodeAddress,
    ]);
    return { getAccount };
};
const Context = createSimpleContext("eq-subaccount", {
    getAccount: () => undefined,
}, useSubAccount);
export const SubAccountProvider = Context.Provider;
export const useAccount = Context.useContext;
//# sourceMappingURL=sub-account.js.map