import { NetworkHelper } from "./NetworkHelper";
import { asyncDelay } from "./util";

export class AI {
  networkHelper: NetworkHelper;
  playerData: any;
  _status = {
    Red: 0,
    Blue: 0,
    letter: "",
    current: "Red",
  };

  constructor(networkHelper: NetworkHelper, playerData: any) {
    this.networkHelper = networkHelper;
    this.playerData = playerData;
  }

  async onFrameEvent(event) {
    console.log("AI get event: " + JSON.stringify(event));
    if (event.type == "SERVER_updateStatus") {
      this._status = JSON.parse(JSON.stringify(event.status));
    } else if (event.type == "SERVER_playerRoll") {
      //玩家需要转盘，待转完之后   进行后续动作
      this._status.letter = event.letter;
      if (this.playerData.color == this._status.current) {
        //TODO:正常8 调试加速 减少AI等待时间  
        await asyncDelay(4);
      }
    } else if (event.type == "SERVER_playerRight") {
      this._status.letter = "";
      this._status[event.color] = event.idx;

      this.changeSide();
    } else if (event.type == "SERVER_playerWrong") {
      this._status.letter = "";
      this.changeSide();
    }

    if (this.playerData.color == this._status.current) {
      if (this._status.letter == "") {
        //TODO:调试加速 2    Math.random() * 3 + 2
        await asyncDelay(Math.random() * 3 + 2);
        this.networkHelper.sendFrame({
          type: "roll",
          uuid: this.playerData.uuid,
        });
      } else {
        //调试加速 2      Math.random() * 3 + 4 
        await asyncDelay(Math.random() * 1 + 10);
        const idx = this.getNextRightIdx();

        if (Math.random() < 0.75) {
          this.networkHelper.sendFrame({
            type: "right",
            idx: idx,
            uuid: this.playerData.uuid,
            color: this.playerData.color,
          });
        } else {
          this.networkHelper.sendFrame({
            type: "wrong",
            uuid: this.playerData.uuid,
            color: this.playerData.color,
          });
        }
      }
    }
  }

  changeSide() {
    if (this._status.current == "Red") {
      this._status.current = "Blue";
    } else {
      this._status.current = "Red";
    }
  }

  getNextRightIdx() {
    const board = cc.find("Canvas/bg/chessBoard/boardItems");
    const startIdx = this._status[this._status.current];
    for (let i = startIdx + 1; i < board.children.length; i++) {
      const targetNode = board.children[i];
      const itemData = targetNode.getComponent("BoardGame2_ItemData");
      if (itemData.letter.toLowerCase() == this._status.letter.toLowerCase()) {
        return i;
      }
    }
    return -1;
  }
}
