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

export class AI {
  networkHelper: NetworkHelper;
  playerData: any;
  _status: any;

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

  async onFrameEvent(event) {
    if (event.type == "SERVER_updateStatus") {

      setTimeout(() => {
        const serverStatus = JSON.parse(JSON.stringify(event.status));
        if (!this._status?.round && serverStatus.round == 1) {
          this._status = serverStatus;
          this.startGame();
        }
        this._status = serverStatus;
      }, this.startDelayTime * 1000);
   
    }
  }

  startGame() {
    const boatIdxList = this._status.boats
      .map((boat, idx) => idx)
      .sort(() => Math.random() - 0.5);
    let time = 6;
    for (let i = 0; i < 16; i++) {
      time += this.params.testDuration + Math.random() * 5;
      setTimeout(() => {
        if (Math.random() < 0.7) {
          this.networkHelper.sendFrame({
            type: "right",
            playerId: this.playerData.uuid,
            boatIdx: boatIdxList[i]
          });
        } else {
          this.networkHelper.sendFrame({
            type: "wrong",
            playerId: this.playerData.uuid,
            boatIdx: boatIdxList[i]
          });
        }
      }, time * 1000);
    }
  }
}
