// @ts-ignore
import TronWeb from 'tronweb';

var tronWeb: any;

export function getTronWeb() {
  return tronWeb;
}

//
// window.setTronRpc = setTronRpc;

export function setTronRpc(rpcUrl = 'https://api.trongrid.io', apiKey = '') {
  const HttpProvider = TronWeb.providers.HttpProvider;
  const fullNode = new HttpProvider(rpcUrl);
  const solidityNode = new HttpProvider(rpcUrl);
  const eventServer = new HttpProvider(rpcUrl);
  // 这个私钥是随机生成的，可以自己生成
  tronWeb = new TronWeb(
    fullNode,
    solidityNode,
    eventServer,
    '5B1E0F83361AD79F8B676CE205B50A6A036876D25F969F290F8017F87CAA9BA3'
  );
  tronWeb.setHeader({'TRON-PRO-API-KEY': apiKey});
}

export async function getTronBalance(account: any) {
  return await tronWeb.trx.getBalance(account);
}

export async function getTronTokenBalance(tokenAddress: any, account: any) {
  const token = await tronWeb.contract().at(tokenAddress);
  return (await token.methods.balanceOf(account).call()).toString();
}

export async function getTronTokenInfo(tokenAddress: any) {
  const token = await tronWeb.contract().at(tokenAddress);
  const [symbol, decimals] = await Promise.all([
    token.methods.symbol().call(),
    token.methods.decimals().call(),
  ]);
  return {
    symbol,
    decimals,
  };
}
