<script setup>
import { useGameStore } from '@/stores/game';
import { usePlayerStore } from '@/stores/player';
import { useBotStore } from '@/stores/bot';
import { ref, onMounted, watch } from 'vue'
import Scrollable from '@/classes/scrollable';
import router from "@/router";
import { useWebsocketStore } from '@/stores/websocket';
import { onBeforeUnmount } from 'vue';

// Init stores
const player = usePlayerStore()
const game = useGameStore()
const bot = useBotStore()

if (game.mode != 'single') useWebsocketStore().init()

// Ref for scrollable
const playerView = ref()
const opponentView = ref()
const scrollPlayer = new Scrollable(playerView)
const scrollOpponent = new Scrollable(opponentView)
// Process a click on a board cell to put down or pick up an item
const makeMove = async (targetCell, event) => {
  if (game.winner != null) return
  //Check if this player turn
  if (game.turn.player != player.id) return
  //Check last move
  let lastMove = game.moves[game.moves.length - 1]
  if (lastMove != undefined && lastMove.player == player.id && lastMove.item.id == 'empty') return
  //Check if this cell already in moves
  if (game.moves.filter((move) => move.player == player.id && move.targetCell == targetCell)[0] != undefined) return
  //Make player move
  let move = await game.makeMove(targetCell)
  if(game.mode == 'single') {
  //Draw cell item
  event.target.classList.add(move.item.type + '-' + move.item.name)
  //Complete move
  await game.completeMove(move)
  }
}
// Return classes for cells
const drawCell = (boardOwner, row, col) => {
  let classes = ''
  let cell = ((row * game.boardSize) + col) - 1
  let showMovesFrom = game.player.id
  if (game.player.id == boardOwner) {
    showMovesFrom = game.opponent.id
    let item = Object.values(game.player.items).filter((item) => item.cells.includes(cell))[0]
    if (item != undefined) {
      classes += ' ' + item.type + '-' + item.name
    }
  }
  let move = Object.values(game.moves).filter((move) => {
    return move.player == showMovesFrom && move.targetCell == cell
  })[0]
  if (move != undefined) classes += ' ' + move.item.type + '-' + move.item.name + ' hit'
  return classes
}
// Draw board on mounted
onMounted(async () => {
  console.log('%c Check player turn after refresh page', 'color:#204ce2', game.turn.player)
  let lastMove = game.moves[game.moves.length - 1]
  if (lastMove != undefined && lastMove.item.id == 'empty' && lastMove.opponent == game.turn.opponent) {
    game.turn.opponent = [game.turn.player, game.turn.player = game.turn.opponent][0]
  }
})
onBeforeUnmount(() => {
  useWebsocketStore().disconnect()
})


watch(
  () => game.turn.player,
  async () => {
  if(game.turn.player == 'bot') {
    await bot.makeMove()
  }
}, { immediate: true })

const newGame = () => {
  let mode = game.mode
  useGameStore().$reset()
  useBotStore().$reset()
  localStorage.removeItem('game')
  localStorage.removeItem('bot')
  game.create(mode)
}
</script>

<template>
  <div class="game">
    <div>
      <h1 v-if="game.winner == null">{{game.turn.player == game.player.id ? $t("game.yourTurn") : $t("game.opponentTurn")}}</h1>
      <h1 v-else>{{ $t("game.over") }}</h1>
    </div>
   <div class="lake-border" v-if="game.winner == null">
      <div class="player-view" :class="[game.turn.player != game.player.id ? 'hide' : 'active']" ref="playerView" 
        @mousedown="scrollPlayer.start($event)" 
        @mousemove="scrollPlayer.move($event)" 
        @mouseup="scrollPlayer.end()" 
        @touchstart="scrollPlayer.start($event)" 
        @touchmove="scrollPlayer.move($event)" 
        @touchend="scrollPlayer.end()"
      >
        <div class="lake">
          <div v-for="key, row in game.boardSize" class="lake-row" :key="'row-' + row">
            <div v-for="col in game.boardSize" class="lake-cell" :class="drawCell(game.opponent.id, row, col)"
              :key="game.opponent.id + '-cell-' + (col + (row * game.boardSize))"
              @click="makeMove((col + (row * game.boardSize)) - 1, $event)">{{ col + (row * game.boardSize) }}</div>
          </div>
        </div>
      </div>

      <div class="opponent-view" :class="[game.turn.player != game.opponent.id ? 'hide' : 'active']" ref="opponentView"
        @mousedown="scrollOpponent.start($event)" 
        @mousemove="scrollOpponent.move($event)" 
        @mouseup="scrollOpponent.end()" 
        @touchstart="scrollOpponent.start($event)" 
        @touchmove="scrollOpponent.move($event)" 
        @touchend="scrollOpponent.end()"
      >
        <div class="lake">
          <div v-for="key, row in game.boardSize" class="lake-row" :key="game.player.id + '-' + row">
            <div v-for="col in game.boardSize" class="lake-cell" :class="drawCell(game.player.id, row, col)"
              :key="game.player.id + '-' + row + '-' + col">{{ col + (row * game.boardSize) }}</div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="game-over">
      <h2>{{ game.winner == game.player.id ? $t("game.win") : $t("game.loose") }}</h2>
      <button class="button-game" @click="newGame()">{{ $t("button.newGame") }}</button>

    </div>
  </div>
</template>

<style scoped>
</style>