import { useCallback, useMemo } from "react";
import { useStored } from "../../hooks/common";
import { createSimpleContext } from "../simple";
import { useObsState } from "../../hooks/rxjs";
const useNetworkHook = ({ networks, lsKey, useSession, }) => {
    const networkIndex = useStored(lsKey ?? "SUBSTRATE_NETWORK");
    const sessionData = useSession?.();
    const session = useObsState(sessionData?.data$);
    const index = useMemo(() => Number(networkIndex.data ?? "0"), [networkIndex.data]);
    const network = useMemo(() => {
        const network = networks[index] ?? networks[0];
        if (session?.networkOverride) {
            network.node = session.networkOverride;
        }
        return network;
    }, [networks, index, session]);
    const setNetworkIndex = useCallback((i) => {
        networkIndex.set(i.toString());
    }, [networkIndex]);
    const selectNetwork = useCallback((netName) => {
        setNetworkIndex(networks.findIndex((n) => n.name === netName));
        setTimeout(() => window.location.reload(), 20);
    }, [networks, setNetworkIndex]);
    return {
        networks,
        network,
        setNetworkIndex,
        selectNetwork,
    };
};
const Context = createSimpleContext("eq-network", {
    networks: [],
    network: undefined,
    setNetworkIndex: () => {
        throw Error("not implemented");
    },
    selectNetwork: () => {
        throw Error("not implemented");
    },
}, useNetworkHook);
export const NetworkProvider = Context.Provider;
export const useNetwork = Context.useContext;
//# sourceMappingURL=network.js.map