import { useGameStore } from '@/stores/game'
import { wait } from '@/common/helpers'
import type { MatchSessionState } from '@/common/interfaces'
import { storeToRefs } from 'pinia'
import { useEventBusStore } from '@/stores/eventBus'

export class SocketIoEventManager {
  gameStore: any = useGameStore()
  eventBus = useEventBusStore()

  handleSessionStateEvent(data: MatchSessionState) {
    const { updateSessionState } = this.gameStore
    updateSessionState(data)
    return {
      status: 'ok'
    }
  }

  handleGameStateEvent(data: any) {
    const { updateGameState } = this.gameStore
    updateGameState(data)
    return {
      status: 'ok'
    }
  }

  handlePlayerStateEvent(data: any) {
    const { updatePlayerState } = this.gameStore
    updatePlayerState(data)
    return {
      status: 'ok'
    }
  }

  async handleCanMakeMoveEvent(data: any) {
    const { canMakeMove, moveToMake } = storeToRefs(this.gameStore)
    const { updateCanMakeMove, setIncomingFreeEnds } = this.gameStore
    setIncomingFreeEnds(data.freeHands)
    updateCanMakeMove(true)
    while (canMakeMove.value) {
      await wait(500)
    }
    return {
      status: 'ok',
      ...moveToMake.value
    }
  }

  async handleCanSelectTileEvent() {
    const { canSelectTile } = storeToRefs(this.gameStore)
    const { updateCanSelectTile } = this.gameStore
    updateCanSelectTile(true)
    while (canSelectTile.value) {
      await wait(500)
    }
    return {
      status: 'ok'
    }
  }

  handleGameFinishedEvent() {
    this.eventBus.publish('game-finished')
  }
}
