import { _decorator, Component, Node } from "cc";
import BaseUI from "../base/BaseUI";
import { AbsM, AbsWrapper } from "../web3/AbsM";
import { SceneUtil } from "../../core_tgx/base/SceneUtils";
import { SceneDef } from "../../scripts/SceneDef";
import { BallUISoloMatch } from "./SoloMatch";
import { UIWaiting } from "../../core_tgx/easy_ui_framework/waiting/UIWaiting";
import { Layout } from "cc";
const { ccclass, property } = _decorator;

@ccclass("Lobby")
export class Lobby extends BaseUI {
  public onLoad(): void {
    let t = new Date().getTime();
    console.log("onLoad", t);
    super.onLoad();
    console.log("onLoad end", new Date().getTime() - t);
    this.setActive("connect_node", true);
    this.setActive("gem_node", false);
    console.log("onLoad end", new Date().getTime() - t);
  }

  //   public setActive(name: string, active: boolean) {}

  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_connect":
        this.connectWallet();
        break;

      case "btn_test_trans":
        this.testTrans();
        break;
      case "btn_play":
        this.beginPlay();
      default:
        break;
    }
  }
  beginPlay() {
    BallUISoloMatch.show();

    // tgx.UIMgr.inst.showUI(UISoloMatch);

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

  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();
  }
}
