import { ERC20ABI } from "./abis/ERC20ABI";
import { Contract, Web3Result as Web3Params } from "./Contract";
import { WalletManager } from "./WalletManager";

export class ContractManager {
  private static _ins: ContractManager = null!;

  private constructor() {}

  public static get ins(): ContractManager {
    return ContractManager._ins ??= new ContractManager();
  }

  public async getZPBalance() {
    let web3Result = WalletManager.ins.getWeb3Result();

    console.log("web3Result", web3Result);
    let contractAddress = "0x8BD8d0f43484E06E86c8667F717A6A80a6F24A2e";
    let tokenAddress = "0x6009950E4B05FBa0F95fe799Ce47b56E2DE4a34F";

    //@ts-ignore
    let contract = await new window.ethers.Contract(
        tokenAddress,
      ERC20ABI,
      web3Result.signer
    );

    console.log("contract", contract, web3Result.account);
    let balance = await this.contractBalance(contract, web3Result.account);
    console.log("balance", balance);
    return balance;
  }

  public async contractBalance(
    contract: any,
    address: string
  ): Promise<number> {
    try {
      //@ts-ignore
      const ethers = window.ethers;
      if (!ethers.utils.isAddress(address)) {
        console.log("Invalid address format");
        // MsgHints.show("Invalid address format");
        return 0;
      }
      const balance = await contract.balanceOf(address);
      console.log(" --- balance", balance);
      let balanceStr = await this.formatEther(balance);
      let balanceNum = Number(balanceStr);
      return balanceNum;
    } catch (error) {
      console.log(" contractBalance error ", error);
      return 0;
    }
  }
  public async formatEther(balance: any): Promise<string> {
    //@ts-ignore
    return Number(Number(window.ethers.utils.formatEther(balance)).toFixed(8));
  }
}
