import { useCallback, useState } from "react";
import { useAsyncMemo } from "../../hooks";
import { createSimpleContext } from "../simple";
import getImports from "./dynamic";
const DEFAULT_CONTEXT = {
    api: undefined,
    extensionDApp: undefined,
    util: undefined,
    utilCrypto: undefined,
    validateSubstrateAddress: (s) => true,
};
const Context = createSimpleContext("eq-base", {
    ...DEFAULT_CONTEXT,
    create: () => {
        throw new Error("not implemented");
    },
}, ({ init }) => {
    const [ready, setReady] = useState(init ?? false);
    const create = useCallback(() => {
        setReady(true);
    }, []);
    const dynImports = useAsyncMemo(async () => {
        const isClient = typeof window !== "undefined";
        if (!isClient || !ready) {
            return DEFAULT_CONTEXT;
        }
        const { api, extensionDApp, utilCrypto, util } = await getImports();
        try {
            await utilCrypto.cryptoWaitReady();
            return { api, extensionDApp, utilCrypto, util };
        }
        catch (e) {
            if (e instanceof Error) {
                console.info({ api, extensionDApp, utilCrypto, util });
                console.error(e.message);
            }
        }
    }, [ready]);
    const validateSubstrateAddress = useCallback((s) => {
        if (!dynImports.data?.util || !dynImports.data?.utilCrypto) {
            return false;
        }
        if (typeof s !== "string")
            return false;
        const { util, utilCrypto } = dynImports.data;
        try {
            utilCrypto.encodeAddress(util.isHex(s) ? util.hexToU8a(s) : utilCrypto.decodeAddress(s));
            return true;
        }
        catch (_) {
            return false;
        }
    }, [dynImports.data?.util, dynImports.data?.utilCrypto]);
    return {
        create,
        api: dynImports.data?.api,
        extensionDApp: dynImports.data?.extensionDApp,
        util: dynImports.data?.util,
        utilCrypto: dynImports.data?.utilCrypto,
        validateSubstrateAddress,
    };
});
export const BaseProvider = Context.Provider;
export const useBase = Context.useContext;
//# sourceMappingURL=base.js.map