import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import type { MatchSessionDto, GameDto, Movement, PlayerDto } from '@/common/interfaces'

export const useGameStore = defineStore('game', () => {
  const sessionState = ref<MatchSessionDto | undefined>(undefined)
  const gameState = ref<GameDto | undefined>(undefined)
  const playerState = ref<PlayerDto | undefined>(undefined)
  const canMakeMove = ref(false)
  const canSelectTile = ref(false)
  const gameFinished = ref(false)
  const moveToMake = ref<Movement | undefined>(undefined)
  const incomingFreeEnds = ref<[number, number] | undefined>(undefined)
  const showReadyButton = ref(false)

  const isSessionStarted = computed(() => sessionState.value !== undefined)
  const amIHost = computed(
    () =>
      sessionState.value !== undefined &&
      playerState.value !== undefined &&
      playerState.value.id === sessionState.value.creator
  )
  const readyForStart = computed(() => playerState.value !== undefined && playerState.value.ready)

  function updateSessionState(newState: MatchSessionDto | undefined) {
    sessionState.value = newState
  }

  function updateGameState(newState: GameDto | undefined) {
    gameState.value = newState
  }

  function updatePlayerState(newState: PlayerDto | undefined) {
    playerState.value = newState
  }

  function updateCanMakeMove(value: boolean) {
    canMakeMove.value = value
  }

  function setMoveToMake(move: Movement) {
    moveToMake.value = move
  }

  function updateCanSelectTile(value: boolean) {
    canSelectTile.value = value
  }

  function setIncomingFreeEnds(freeEnds: [number, number]) {
    incomingFreeEnds.value = freeEnds
  }

  function setShowReadyButton(value: boolean) {
    showReadyButton.value = value
  }

  function updateGameFinished(value: boolean) {
    gameFinished.value = value
  }

  return {
    sessionState,
    gameState,
    playerState,
    canMakeMove,
    moveToMake,
    incomingFreeEnds,
    canSelectTile,
    showReadyButton,
    readyForStart,
    gameFinished,
    updateSessionState,
    updateGameState,
    updatePlayerState,
    updateCanMakeMove,
    setMoveToMake,
    setIncomingFreeEnds,
    updateCanSelectTile,
    setShowReadyButton,
    updateGameFinished,
    isSessionStarted,
    amIHost
  }
})
