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

export class GameServer {
  playerList = [];
  playerMaxNumber = 0;
  networkHelper: NetworkHelper = null;
  nameList = [
    "Chris",
    "Benny",
    "Leslie",
    "Devin",
    "Sam",
    "Kerry",
    "Joey",
    "Hailey",
    "Fred",
    "Arrow",
    "Tony",
    "Michael",
  ];
  headUrls = [
    "http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png",
    "http://staging-teach.cdn.ireadabc.com/f596e586a31ac2813b1702557941c022.png",
    "http://staging-teach.cdn.ireadabc.com/f0f396c52c42239913fd94523db979fa.png",
    "http://staging-teach.cdn.ireadabc.com/9f2d2ef622fa33d4e2abcbdc4b40ab6a.png",
    "http://staging-teach.cdn.ireadabc.com/f40ce4a8630039c4cf48a63fc1399c52.png",
  ];

  jumpList = [
    // { from: 2, to: 11 },
    // { from: 3, to: 7 },
    // { from: 8, to: 18 },
    // { from: 9, to: 2 },
    // { from: 12, to: 15 },
    // { from: 13, to: 1 },
    // { from: 21, to: 5 },
    // { from: 24, to: 16 },
  ];

  constructor(playerMaxNumber, networkHelper) {
    this.playerMaxNumber = playerMaxNumber;
    this.networkHelper = networkHelper;

    this._timeoutIds = [];
    this._intervalIds = [];

    this.headUrls = this.headUrls.sort((a, b) => RandomInt(2) - 1);
    this.nameList = this.nameList.sort((a, b) => RandomInt(2) - 1);

    this.networkHelper.startFrameSync();
  }

  async addPlayer(player) {
    console.log("addPlayer");
    this.playerList.push({
      name: this.nameList.splice(0, 1)[0],
      uuid: player.uuid,
      color:
        player.uuid == this.networkHelper.room.roomInfo.owner ? "Red" : "Blue",
      isAI: player.isAI,
      headUrl: this.headUrls.splice(0, 1)[0],
    });

    if (player.isAI) {
      await asyncDelay(1);
      this.networkHelper.sendFrame({
        type: "SERVER_allPlayerInfo",
        playerData: this.playerList,
      });
      if (this.playerList.length == this.playerMaxNumber) {
        this.networkHelper.closeRoom();
        await asyncDelay(0.5);
        this.startGame();
        this.startAI();
      }
    }
  }

  gameStatus = {
    Red: 0,
    Blue: 0,
    letter: "",
    current: "Red",
  };
  startGame() {
    this.networkHelper.sendFrame({
      type: "SERVER_updateStatus",
      status: this.gameStatus,
    });
  }

  onPlayerJoin(event) {
    this.addPlayer({
      uuid: event.data.joinPlayerId,
      isAI: false,
    });
  }

  _aiPlayerList = [];
  startMatch() {
    for (let i = 0; i < this.playerMaxNumber; i++) {
      this._timeoutIds.push(
        setTimeout(() => {
          const count = this.playerMaxNumber - this.playerList.length;
          if (count > 0) {
            const playerInfo = {
              uuid: "ai_" + i,
              isAI: true,
              color: "Blue",
            };
            this._aiPlayerList.push(new AI(this.networkHelper, playerInfo));
            this.addPlayer(playerInfo);
          }
          //TODO:调试加速
        }, 10000)//RandomInt(10000, 15000)
      );
    }
  }

  async onFrameEvent(data) {
    if (this.gameStatus['gameOver']) {
      return;
    }
    if (data.type == "roll") {
      const letterList = this.getLetterList();
      console.log('server letterList: ', letterList);
      if (letterList.length > 0) {
        if (this.gameStatus.letter == "") {
          // let max = Math.max(9, 0);
          // let letter = letterList[max];//[RandomInt(letterList.length) % 3];//转盘只有1-3
          // if (this.gameStatus.current == 'Blue') {
          //   letter = letterList[0]
          // }
          let letter = letterList[RandomInt(letterList.length) % 3];
          this.gameStatus.letter = letter;
          this.networkHelper.sendFrame({
            type: "SERVER_playerRoll",
            letter: letter,
          });
        } else {
          console.log('汪汪汪3')
        }
      } else {
        this.networkHelper.sendFrame({
          type: "SERVER_playerWin",
          color: this.gameStatus.current,
        });
        this.gameStatus['gameOver'] = true;
      }
    } else if (data.type == "playerInfo") {
      const player = this.playerList.find(p => p.uuid == data.playerId);
      player.name = data.playerName;
      player.headUrl = data.playerHeadUrl;
      this.networkHelper.sendFrame({
        type: "SERVER_allPlayerInfo",
        playerData: this.playerList,
      });
      if (this.playerList.length == this.playerMaxNumber) {
        this.networkHelper.closeRoom();
        await asyncDelay(0.5);
        this.startGame();
        this.startAI();
      }
    } else if (data.type == "right") {
      if (this.gameStatus.letter != "") {
        this.gameStatus.letter = "";

        this.gameStatus[data.color] = data.idx;
        const jump = this.jumpList.find(jump => parseInt(jump.from) == parseInt(data.idx));
        const letterList = this.getLetterList();
        // console.log("letterList = " + JSON.stringify(letterList));
        if (letterList.length > 0) {
          if (jump) {
            this.gameStatus[data.color] = parseInt(jump.to);
          }
          this.changeSide();
          this.networkHelper.sendFrame({
            type: "SERVER_playerRight",
            idx: this.gameStatus[data.color],
            uuid: data.uuid,
            color: data.color,
          });
        } else {
          this.networkHelper.sendFrame({
            type: "SERVER_playerWin",
            color: this.gameStatus.current,
          });
          this.gameStatus['gameOver'] = true;
        }
      } else {
        console.log('汪汪汪');
      }
    } else if (data.type == "wrong") {
      if (this.gameStatus.letter != "") {
        this.gameStatus.letter = "";
        console.log("data = " + JSON.stringify(data));
        // this.gameStatus[data.color] = data.idx;
        this.changeSide();
        this.networkHelper.sendFrame({
          type: "SERVER_playerWrong",
          uuid: data.uuid,
          color: data.color,
        });
      } else {
        console.log('汪汪汪2');
      }
    } else {
      this._aiPlayerList.forEach((ai: AI) => {
        ai.onFrameEvent(data);
      });
    }
  }

  getLetterList() {
    const board = cc.find("Canvas/bg/chessBoard/boardItems");
    const color = this.gameStatus.current;
    // console.log("color = " + color);
    // console.log("this.gameStatus = " + JSON.stringify(this.gameStatus));
    const startIdx = this.gameStatus[color];
    // console.log("startIdx = " + startIdx);

    const letterList = [];
    for (let i = startIdx + 1; i < board.children.length - 1; i++) {
      const targetNode = board.children[i];
      const itemData = targetNode.getComponent("BoardGame2_ItemData");
      const nodeLetter = itemData.letter.toUpperCase();
      if (!letterList.find((letter) => letter == nodeLetter)) {
        letterList.push(nodeLetter);
      }
    }
    return letterList;
  }

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

  startAI() {
    this.playerList
      .filter((player) => player.isAI == true)
      .forEach((player) => { });
  }

  _timeoutIds = null;
  _intervalIds = null;
  // 生命周期
  onDestroy() {
    this._timeoutIds.forEach((id) => {
      clearTimeout(id);
    });
    this._intervalIds.forEach((id) => {
      clearInterval(id);
    });
  }
}
