import { useGameStore } from '@/stores/game'
import { wait } from '@/common/helpers'
import type { MatchSessionDto, Movement, SocketEvent } from '@/common/interfaces'
import { storeToRefs } from 'pinia'
import { useEventBusStore } from '@/stores/eventBus'
import type { SocketIoClientService } from '@/services/SocketIoClientService'

export class SocketIoEventManager {
  gameStore: any = useGameStore()
  eventBus = useEventBusStore()
  callbacksMap: Map<string, any> = new Map()

  constructor(private socketService: SocketIoClientService) {}

  handleGameEvent(gameEvent: SocketEvent) {
    const { event, data } = gameEvent
    switch (event) {
      case 'update-match-session-state':
        this.updateSessionState(data)
        break
      case 'update-game-state':
        this.updateGameState(data)
        break
      case 'update-player-state':
        this.updatePlayerState(data)
        break
      case 'server:player-turn':
        this.onCanMakeMoveEvent(data)
        break
      default:
        this.eventBus.publish(event, data)
        break
    }
  }

  handleGameEventAck(gameEvent: SocketEvent, callback: any) {
    const { event, data } = gameEvent
    switch (event) {
      // case 'ask-client-for-move':
      //   return this.handleCanMakeMoveEvent(data, callback)
      default:
        this.eventBus.publish(event, data)
        break
    }
  }

  private updateSessionState(data: MatchSessionDto) {
    const { updateSessionState } = this.gameStore
    updateSessionState(data)
  }

  private updateGameState(data: any) {
    const { updateGameState } = this.gameStore
    updateGameState(data)
  }

  private updatePlayerState(data: any) {
    const { updatePlayerState } = this.gameStore
    updatePlayerState(data)
  }

  private onCanMakeMoveEvent(data: any) {
    const { setIncomingFreeEnds } = this.gameStore
    setIncomingFreeEnds(data.firstMove ? undefined : data.freeHands)
    this.eventBus.publish('game:player-turn-started', data)
  }

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