<script setup lang="ts">
import type { MatchSessionState, GameState, PlayerDto } from '@/common/interfaces'
import { onMounted, onUnmounted, ref, watch, inject } from 'vue'
import { Game } from '@/game/Game'
import { useGameStore } from '@/stores/game'
import { useEventBusStore } from '@/stores/eventBus'
import type { LoggingService } from '@/services/LoggingService'
import { storeToRefs } from 'pinia'

const logger: LoggingService = inject<LoggingService>('logger') as LoggingService
const emit = defineEmits(['move'])
const socketService: any = inject('socket')

const gameStore = useGameStore()
const eventBus = useEventBusStore()
const { playerState, sessionState } = storeToRefs(gameStore)

let appEl = ref<HTMLElement | null>(null)

const game = new Game(
  {
    width: 1200,
    height: 650,
    boardScale: 0.8,
    handScale: 1
  },
  emit,
  socketService,
  playerState.value?.id || '',
  sessionState.value?.id || ''
)

onMounted(async () => {
  if (appEl.value === null) return
  const canvas = await game.setup()
  appEl.value.appendChild(canvas)
  await game.preload()
  await game.start()

  eventBus.subscribe('game-finished', () => {
    game.gameFinished()
  })

  watch(
    () => gameStore.canMakeMove,
    (value: boolean) => {
      game.setCanMakeMove(value)
    }
  )

  watch(
    () => gameStore.gameState,
    (value: GameState | undefined) => {
      if (value === undefined) return
      logger.debug('gameState-------------------------------------- :>> ', value)
      game.board?.setState(value, playerState.value?.id ?? '')
    }
  )

  watch(
    () => gameStore.sessionState,
    (value: MatchSessionState | undefined) => {
      if (value === undefined) return
      // logger.debug('gameSessionState-------------------------------------- :>> ', value)
    }
  )

  watch(
    () => gameStore.playerState,
    (value: PlayerDto | undefined) => {
      if (value === undefined) return
      game.hand.update(value as PlayerDto)
    }
  )

  // mockMove(game, [6, 6], 'left')
  // mockMove(game, [6, 4], 'left')
  // mockMove(game, [4, 4], 'left')
  // mockMove(game, [4, 0], 'left')
  // mockMove(game, [0, 0], 'left')
  // mockMove(game, [2, 0], 'left')
  // mockMove(game, [2, 2], 'left')
  // mockMove(game, [6, 5], 'right')
  // mockMove(game, [5, 5], 'right')
  // mockMove(game, [5, 1], 'right')
  // mockMove(game, [3, 1], 'right')
  // mockMove(game, [3, 0], 'right')
  // mockMove(game, [5, 0], 'right')
})

onUnmounted(() => {
  game.destroy()
})
</script>

<template>
  <div ref="appEl" class="game-app"></div>
</template>

<style scoped>
.game-app {
  position: relative;
  z-index: 10;
}
</style>
