import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { createRef, forwardRef, useEffect, useImperativeHandle, useMemo, useState, } from "react";
import { useWallet, UseWalletProvider } from "use-wallet";
import useAsyncControl from "../../hooks/useAsyncControl";
function _WalletConnectionWrapper(props, ref) {
    return (_jsx(UseWalletProvider, { children: _jsx(Content, { compRef: ref || createRef(), ...props }) }));
}
/**
 * This component handles a lot of cenarios when dealing with the wallet connection to different providers (ex: Metamask)
 **/
function _BaseWalletConnectionWrapper(props, ref) {
    return _jsx(Content, { compRef: ref || createRef(), ...props });
}
function Content({ ProviderUnavailable, ChainIdInvalid, chain, Content: ProvidedContentWrapper, compRef, children, }) {
    const wallet = useWallet();
    const connectionAsyncWrapper = useAsyncControl();
    const connect = async () => {
        await connectionAsyncWrapper.process(async () => {
            await wallet.connect("injected");
            localStorage.setItem("auto_connect", "true");
        });
    };
    const disconnect = () => {
        wallet.reset();
        localStorage.removeItem("auto_connect");
    };
    useEffect(() => {
        const autoConnect = !!localStorage.getItem("auto_connect");
        if (autoConnect && !wallet.account)
            connect();
    }, []);
    useImperativeHandle(compRef, () => ({
        connect,
        disconnect,
    }), [wallet]);
    const [isProviderAvailable] = useState(() => !!window.ethereum);
    /**
     * true - Mostrar o conteudo (ex: form de transferencia)
     * false - Mostrar o botão de trocar a chain
     *
     * undefined ???
     */
    const isChainIdValid = useMemo(() => chain
        ? wallet.isConnected()
            ? wallet.chainId === chain.id
            : true
        : undefined, [wallet, chain?.id]);
    async function changeChainId() {
        try {
            await window.ethereum.request({
                method: "wallet_switchEthereumChain",
                params: [
                    {
                        chainId: `0x${chain.id.toString(16).padStart(2, "0")}`,
                    },
                ],
            });
        }
        catch (e) {
            switch (e.code) {
                case 4902:
                    await window.ethereum.request({
                        method: "wallet_addEthereumChain",
                        params: [
                            {
                                chainId: `0x${chain.id.toString(16).padStart(2, "0")}`,
                                chainName: chain.name,
                                rpcUrls: [chain.rpcUrl],
                                blockExplorerUrls: [chain.explorerUrl],
                                nativeCurrency: {
                                    symbol: chain.currency,
                                    decimals: 18,
                                },
                            },
                        ],
                    });
                default:
                    throw e;
            }
        }
    }
    const ContentWrapper = ProvidedContentWrapper;
    return (_jsxs(_Fragment, { children: [ProviderUnavailable && !isProviderAvailable && _jsx(ProviderUnavailable, {}), ChainIdInvalid && !isChainIdValid && (_jsx(ChainIdInvalid, { changeChainId: changeChainId })), _jsx(ContentWrapper, { ...connectionAsyncWrapper, isChainIdValid: isChainIdValid, isProviderAvailable: isProviderAvailable, isConnectedAndValidChain: isChainIdValid && wallet.isConnected(), connect: connect, disconnect: disconnect, changeChainId: changeChainId, chainId: wallet.chainId, isConnected: wallet.isConnected(), wallet: wallet.account, children: children })] }));
}
/**
 * This component handles some cenarios when dealing with the wallet connection to different providers (ex: Metamask)
 **/
const WalletConnectionWrapper = forwardRef(_WalletConnectionWrapper);
export default WalletConnectionWrapper;
export const BaseWalletConnectionWrapper = forwardRef(_BaseWalletConnectionWrapper);
//# sourceMappingURL=WalletConnectionWrapper.js.map