import { BscConnector } from '@binance-chain/bsc-connector';
import EventDispatcher from './EventDispatcher.js';

let bscConnector;
let isRegister = false;
let CodeEnum;
let walletMgr;

async function init(_walletMgr,fun){
    walletMgr = _walletMgr;
    CodeEnum  = walletMgr.ReturnCodeEnum;
    bscConnector = new BscConnector({
        supportedChainIds: [56, 97] 
    })
    try {
        registerWalletEvent();

    } catch (error) {
        //alert('Please install the MetaMask plug-in and unlock your Ethereum account');
        return ;
    }
    connectWallectAccount(fun)
}

async function connectWallectAccount(fun){
    
    let act = await bscConnector.activate();
    let account =  await bscConnector.getAccount();
    walletMgr.currentAccount =  account;
    let chainId = await bscConnector.getChainId();
    walletMgr.currentChaidId = chainId;

    if(walletMgr.currentChaidId == walletMgr.currentChain[0].chainId && walletMgr.currentAccount != null){
        fun({code:CodeEnum.SUCCESS,data:walletMgr.currentAccount});
        walletMgr.crateContract(act.provider)
    }else{
        fun({code:CodeEnum.NOT_CURRENT_CHAIN,data:"Please switch the chain"});
    }

}

function registerWalletEvent(){
    if(isRegister) return;
        else isRegister = true;

    BinanceChain.on('chainChanged', onChainChanged);
    BinanceChain.on('accountsChanged',onAccountsChanged);
    BinanceChain.on('disconnect',onDisConnect);
}

function close(){
    
}

function onDisConnect(e){

    EventDispatcher.Dispatch(EventDispatcher.Enum.loginOut);
}

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

}

function onAccountsChanged(e){
    if(walletMgr.getWalletCurType() != walletMgr.WalletEnum.BinanceChain)return;

    if(!(typeof e=='string'))e = e[0];
    walletMgr.currentAccount = e;
    if (localStorage.getItem('authaddress') != e)
        EventDispatcher.Dispatch(EventDispatcher.Enum.loginOut);
    EventDispatcher.Dispatch(EventDispatcher.Enum.accountsChanged_wallet, e);
}

function sign(msg,func){
    BinanceChain.request({method: "eth_sign", params: [walletMgr.currentAccount, msg]}).then((sig) => {
        console.log('SIGNED:' + sig)
        func({code:CodeEnum.SUCCESS,data:sig});
    }).catch((error)=>{
        console.log('SIGNED:' , error)
        func({code:CodeEnum.SIGNATURE_FAILED,data:error});
    })
}

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