import { ygopro } from "@/api";
import { roomStore } from "@/stores";

export default function handleHsPlayerChange(pb: ygopro.YgoStocMsg) {
  const change = pb.stoc_hs_player_change;

  if (change.pos > 1) {
    console.log("Currently only supported 2v2 mode.");
  } else {
    switch (change.state) {
      case ygopro.StocHsPlayerChange.State.UNKNOWN: {
        console.log("Unknown HsPlayerChange State");

        break;
      }
      case ygopro.StocHsPlayerChange.State.MOVE: {
        // TODO: 这个分支可能有BUG，后面注意一下
        console.log("Player " + change.pos + " moved to " + change.moved_pos);

        const player = roomStore.players.splice(change.pos, 1);
        const insertIndex =
          change.pos > change.moved_pos
            ? change.moved_pos
            : change.moved_pos - 1;
        roomStore.players.splice(insertIndex, 0, ...player);

        break;
      }
      case ygopro.StocHsPlayerChange.State.READY:
      case ygopro.StocHsPlayerChange.State.NO_READY:
      case ygopro.StocHsPlayerChange.State.LEAVE: {
        // 因为某种原因，当state为`LEAVE`的时候不能把它从`players`中去掉，
        // 只能修改状态然后UI上做特化处理
        roomStore.players[change.pos].state = change.state;
        break;
      }
      case ygopro.StocHsPlayerChange.State.TO_OBSERVER: {
        roomStore.players.splice(change.pos, 1);
        roomStore.observerCount += 1;
        break;
      }
      default: {
        break;
      }
    }
  }
}
