import { _decorator, Component, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { Hall } from "../hall/Hall";
import {
  BindGameInputLayer,
  BindGameInputLayerListener,
} from "./BindGameInputLayer";
import { Tips } from "../../scripts/mgr/Tips";
import { BindGameM } from "../../scripts/api/BindGameM";
import UserM from "../../scripts/api/UserM";
import GameM from "../../scripts/api/GameM";
const { ccclass, property } = _decorator;

@ccclass("BindGameLayer")
export class BindGameLayer
  extends BaseUI
  implements BindGameInputLayerListener
{
  static async show() {
    let layer = await Hall.ins.showLayer("prefab/layer/BindGameLayer");
    layer.getComponent(BindGameLayer).init();
  }

  protected onLoad(): void {
    super.onLoad();
    this.FindNode("BindGameItem").active = false;
  }

  private async init() {
    await UserM.ins.refreshInfo();

    let isPvzLinked: boolean = await UserM.ins.getPvzLinked();
    this.setText(
      "lbl_link_pvz_state",
      "Link Status: " + (isPvzLinked ? "✅" : "❌")
    );

    if (isPvzLinked) {
      let pvz_user_name = UserM.ins.data.gameList.find(
        (item) => item.gameId == 1
      )?.gameUser?.userName;
      if (pvz_user_name != null && pvz_user_name.length > 0) {
        this.setText("lbl_link_pvz_user_name", "@" + pvz_user_name);
      }
    }
  }

  OnInput(gameId: number, input: string): void {
    this.startBindGame(gameId, input);
  }
  async startBindGame(gameId: number, input: string) {
    let result = await GameM.ins.bindGame(gameId, input);
    if (result != null) {
      this.init();

      // Tips.show("Waiting for binding...");
      // this.setText("lbl_code_banana", input);
    }
  }

  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_bind_game_pvz":
        // Tips.show("Coming soon");
        let gameId = 1;
        BindGameInputLayer.show(gameId, this);
        break;
    }
  }
}
