
import WalletConnectProvider from "@walletconnect/web3-provider";
import EventDispatcher from './EventDispatcher.js';
import BigNumber from 'bignumber.js';
let Web3 = require('web3')
let walletMgr;
let provider;
let codeEnum

function init(_walletMgr,fun){
    walletMgr = _walletMgr;
    codeEnum = walletMgr.ReturnCodeEnum;
    createProvider();
    connectWallectAccount(fun)
}

async function connectWallectAccount(fun){
    await provider.enable();
    registerWalletEvent();
    const web3 = new Web3(provider);
    const accounts = await web3.eth.getAccounts();
    walletMgr.currentAccount = accounts[0];
    const chainId = await web3.eth.getChainId();
    walletMgr.currentChaidId = "0x"+(new BigNumber(chainId)).toString(16);
    if(walletMgr.currentChaidId == walletMgr.currentChain[0].chainId && walletMgr.currentAccount != null){
        fun({code:codeEnum.SUCCESS,data:walletMgr.currentAccount});
        walletMgr.crateContract(provider);
    }else{
        fun({code:codeEnum.NOT_CURRENT_CHAIN,data:"Please switch to BSC network"});
    }

}

function createProvider(){
    provider = new WalletConnectProvider({
        infuraId: "27e484dcd9e3efcfd25a83a78777cdf1",
        rpc: {
            56: 'https://bsc-dataseed1.binance.org',
            97:"https://data-seed-prebsc-1-s1.binance.org:8545/",
        },
        "chainId":new BigNumber(walletMgr.currentChain[0].chainId).toNumber(),
        "networkId":new BigNumber(walletMgr.currentChain[0].chainId).toNumber(),
    })
    disconnect();
}

function registerWalletEvent(){
    provider.on('chainChanged', onChainChanged);
    provider.on('accountsChanged',onAccountsChanged);
    provider.on('disconnect',onDisConnect);
}

function disconnect(){
    if(provider == null) return;
    provider.disconnect();
    provider.close();
}

function close(){
    disconnect();
}

function onChainChanged(e){
    walletMgr.currentChaidId = e;
    if ( walletMgr.currentChain[0].chainId != e){
        EventDispatcher.Dispatch(EventDispatcher.Enum.loginOut);
        disconnect()
    }
    EventDispatcher.Dispatch(EventDispatcher.Enum.chainChanged_wallet, e);

}

function onAccountsChanged(e){
    walletMgr.currentAccount = e;
    if (localStorage.getItem('authaddress') != e){
        EventDispatcher.Dispatch(EventDispatcher.Enum.loginOut);
        disconnect();
    }
    EventDispatcher.Dispatch(EventDispatcher.Enum.accountsChanged_wallet, e);
}

function onDisConnect(e){
    EventDispatcher.Dispatch(EventDispatcher.Enum.loginOut);
}

export default{
    connectWallectAccount,
    init,
    close,
    createProvider,
}