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

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

  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) {
        // await asyncDelay(Math.random() * 3 + 12);
        await asyncDelay(15);
      }
    } 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) {
      await asyncDelay(Math.random() * 3 + 4);
      if (this._status.letter == "") {
        await asyncDelay(Math.random() * 3 + 2);
        this.networkHelper.sendFrame({
          type: "roll",
          uuid: this.playerData.uuid,
        });
      } else {
        const idx = this.getNextRightIdx();
        if (Math.random() < 0.9) {
          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("ItemData");
      if (itemData.letter.toLowerCase() == this._status.letter.toLowerCase()) {
        return i;
      }
    }
    return -1;
  }
}
