import detectEthereumProvider from '@metamask/detect-provider'
import eventDispatcher from './EventDispatcher.js';
// import constants from './Constants.js';
var tp = require('tp-js-sdk')

let provider;
let CodeEnum;
let walletMgr;
function registerWalletEvent(){
    ethereum.on('chainChanged', onChainChanged);
    ethereum.on('accountsChanged',onAccountsChanged);

}

function close(){
    if(typeof ethereum.removeListener !="undefined"){
        ethereum.removeListener('chainChanged', onChainChanged);
        ethereum.removeListener('accountsChanged',onAccountsChanged);
    }  
}

function onChainChanged(e){
    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(!(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);
}


async function init(_walletMgr,fun){
    walletMgr = _walletMgr;
    CodeEnum =walletMgr.ReturnCodeEnum;
    provider = await detectEthereumProvider()
 
    if (provider == null){
        if(tp.isConnected())
            alert('Please switch to BSC network');
        else
            alert('Please install the MetaMask plug-in and unlock your Ethereum account');
        return;
    }
    registerWalletEvent();
    connectWallectAccount(fun);
    walletMgr.crateContract(provider)
}


function addEthereumChain(fun){
    console.log(walletMgr.currentChain);
    provider.request({ 
        method: 'wallet_addEthereumChain',
        params :walletMgr.currentChain
        })
        .then((req)=>{
            let reqInfo ={
                code : CodeEnum.SUCCESS,
                data :req,
            }
            walletMgr.currentChaidId = walletMgr.currentChain[0].chainId;
            fun(reqInfo);
        }).catch((error) => {
            fun(error);
        });
}

function requestAccounts(func){
    provider.request({ method: 'eth_requestAccounts' }).then((req)=>{
        let reqInfo ={
            code : CodeEnum.SUCCESS,
            data :req[0],
        }
        console.log(req);
        walletMgr.currentAccount = req[0];
        func(reqInfo);
    }).catch((error)=>{
        func(error);
    })
}

function connectWallectAccount(func){
    addEthereumChain((req)=>{
        console.log(req);
        if (req.code == CodeEnum.SUCCESS){
            requestAccounts(func);
        }else{
            func(req);
        }
    });
}

function addTokens(info){
    provider.request({ 
        method: 'wallet_watchAsset',
        params: {
            type:'ERC20',
            options:{
                address:info.address,
                symbol:info.symbol,
                decimals:info.decimals,
                image:'http://www.mymymoba.com/favicon.ico'
            }
        }
    }).then((req)=>{
       console.log(req);
    }).catch((error)=>{
        console.log(error);
    })
}

export default {
    init,
    registerWalletEvent,
    connectWallectAccount,
    addTokens,
    close,
}
