import Web3 from 'web3';
import detectEthereumProvider from '@metamask/detect-provider';
import { message } from 'antd';

let provider: any;

export const web3 = new Web3();
if (typeof window.ethereum !== 'undefined') {
  web3.eth.defaultAccount = window.ethereum.selectedAddress;
}

export async function initWeb3() {
  provider = await detectEthereumProvider();

  if (!provider) {
    console.log('请安装MetaMask');
    return false;
  }

  try {
    web3.setProvider(provider);
    const accounts = await provider.request({
      method: 'eth_requestAccounts',
    });
    web3.eth.defaultAccount = accounts[0];
    return true;
  } catch (reason) {
    switch (reason) {
      case 'Already processing eth_requestAccounts. Please wait.': // 已有请求存在
        message.warning('请打开MetaMask完成授权');
        break;
      case 'User rejected provider access': //如果用户拒绝了登录请求
        message.warning('请同意登录请求');
        break;
      default:
        // 本不该执行到这里，但是真到这里了，说明发生了意外
        message.warning('登录出错！err:' + reason);
        break;
    }
  }
  return false;
}
