import { _decorator, Component, Node } from "cc";
import BaseUI from "../base/BaseUI";
import { UIWaiting } from "../../core_tgx/easy_ui_framework/waiting/UIWaiting";
import { AbsWrapper, AbsM } from "../web3/AbsM";
const { ccclass, property } = _decorator;

@ccclass("TopBar")
export class TopBar extends BaseUI {
  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_connect":
        this.connectWallet();
        break;
    }
  }

  protected onLoad(): void {
    super.onLoad();
    if (AbsM.ins.isConnected) {
      this.setActive("connect_node", false);
      this.setActive("gem_node", true);
    } else {
      this.setActive("connect_node", true);
      this.setActive("gem_node", false);
    }
  }

  private _w: AbsWrapper;

  async connectWallet() {
    UIWaiting.show("Connecting Wallet");
    try {
      let wrapper: AbsWrapper = await AbsM.ins.connectWallet();
      this._w = wrapper;
    } catch (e) {
      UIWaiting.hide();
      return;
    }

    let balance = await AbsM.ins.getBalance(this._w);
    // console.log("balance", balance);
    this.setActive("lbl_eth_balance", true);
    if (balance <= 0) {
      this.setText("lbl_eth_balance", "<0.00");
    } else if (balance < 0.01) {
      this.setText("lbl_eth_balance", "<0.01");
    } else {
      this.setText("lbl_eth_balance", "" + balance.toFixed(2) + "");
    }
    this.setActive("connect_node", false);
    this.setActive("gem_node", true);

    // this.FindAs("top_layout", Layout).updateLayout();
    UIWaiting.hide();
  }

  async testTrans() {
    const signature = await this._w.result.walletClient.sendTransaction({
      to: "0x273B3527BF5b607dE86F504fED49e1582dD2a1C6",
      data: "0x69",
    });
    console.log("signature", signature);
  }
}
