import MsgData from "./msgDate_L5R3_GuessingGame";
import { MsgType } from "./msgType_L5R3_GuessingGame";
import { NetworkHelper } from "./NetworkHelper_L5R3_GuessingGame";
import { asyncDelay } from "./util_L5R3_GuessingGame";

const countDelay = 4; // 距离上次答对 间隔4s 开始答题下一题
export class AI {
  networkHelper: NetworkHelper;
  playerData: any;

  _startAi: boolean = false;
  _answerpro = 0;
  private _gameData: MsgData;
  private _countDelay: number;
  private _stepIndex: any;
  wordList: any;
  private _tryAnswer: boolean;
  private _otherWord: any;
  constructor(networkHelper: NetworkHelper, playerData: any, wordList) {
    this.networkHelper = networkHelper;
    this.playerData = playerData;
    this.wordList = wordList;
    this._tryAnswer = false;
  }

  async onFrameEvent(data) {
    // console.log("AI get event: " + data);

    let type: MsgType = data.type;
    let msgData = data.data;

    if (type == MsgType.ROOM_ST) {

      this._gameData = new MsgData(JSON.parse(msgData));

      if (!this._startAi) return;

      if (this._gameData.Round == 1) {



      } else if (this._gameData.Round == 2) {

        this._countDelay--;
        if (this._countDelay <= 0) {
          if (Math.random() > 0.5) {

            this._sendMsg({ type: MsgType.USER_REQ_WOED, data: { word: this._otherWord, uuid: this.playerData.uuid } })
          }

          this._countDelay = 100000;
        }

      }
    }
    else if (type == MsgType.ROUND_START_EV) {
      let data = msgData;
      if (data.round == 1) {

        let index = Math.floor(Math.random() * this.wordList.length * 0.99);
        let word = this.wordList[index];
        this._sendMsg({
          type:
            MsgType.USER_REQ_ADD_WOED,
          data: {
            uuid: this.playerData.uuid,
            word: word,
          }
        })
      } else {

        data.list.forEach((val) => {
          if (val.uuid != this.playerData.uuid) {
            this._otherWord = val.word;
          }
        })

        this._startAi = true;
        this._stepIndex = data.index;
        this._countDelay = Math.floor(70 + Math.random() * 15);
      }
    } else if (type == MsgType.ROUND_END_EV) {
      let data = msgData;
      if (data.round == 1) {
        this._countDelay = 500000000;
      } else {
        this._countDelay = 500000000;
      }
    }
  }

  _sendMsg(data: { type: MsgType, data: any }) {
    this.networkHelper.sendFrame({
      type: data.type,
      data: data.data
    });
  }

}
