<script setup lang="ts">
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
import useClipboard from 'vue-clipboard3'

import { useGameStore } from '@/stores/game'
import { storeToRefs } from 'pinia'
import { LoggingService } from '@/services/LoggingService'

let seed = ref('')

const router = useRouter()
const gameStore = useGameStore()
const { toClipboard } = useClipboard()
const socketService: any = inject('socket')
const logger: LoggingService = inject<LoggingService>('logger') as LoggingService

const { readyForStart, sessionState, isSessionStarted, playerState } = storeToRefs(gameStore)

async function setPlayerReady() {
  logger.debug('Starting game')
  if (!sessionState.value) {
    logger.error('No session found')
    return
  }
  await socketService.sendMessageWithAck('playerReady', {
    user: 'arhuako',
    sessionId: sessionState.value.id
  })
  readyForStart.value = true
}

async function createMatch() {
  logger.debug('Creating match')
  socketService.sendMessageWithAck('createSession', { user: 'arhuako' })
}

async function joinMatch() {
  const sessionId = sessionState?.value?.id
  const playerId = playerState?.value?.id
  if (sessionId && playerId) {
    await socketService.sendMessageWithAck('joinSession', {
      user: 'pepe',
      sessionId: sessionId
    })
    // sessionId.value = response.sessionId
    // playerId.value = response.playerId
  }
}

async function startMatch() {
  if (sessionState.value && sessionState.value.id) {
    router.push({ name: 'game' })
  }
}
</script>

<template>
  <div class="block home">
    <section class="section">
      <h1 class="title is-2">Welcome to the Player's Home Page</h1>
      <div class="block">
        <p>This is a protected route.</p>
        <p>{{ sessionState || 'No session' }}</p>
        <p>{{ playerState?.ready || 'No player state' }}</p>
        <p>Session started: {{ isSessionStarted }}</p>
      </div>
      <div class="block">
        <input class="input" style="margin-bottom: 0" v-model="seed" placeholder="Seed" />
      </div>
      <button class="button" @click="createMatch" v-if="!isSessionStarted">
        Create Match Session
      </button>
      <button class="button" @click="setPlayerReady" v-if="isSessionStarted">
        <span v-if="!readyForStart">Ready</span><span v-else>Unready</span>
      </button>
      <button class="button" @click="startMatch" v-if="readyForStart">
        <span>Start</span>
      </button>
    </section>
    <section class="section available-sessions">
      <h2 class="title is-4">Available Sessions</h2>
      <div class="bloc">
        <p>There are no available sessions at the moment.</p>
      </div>
    </section>
  </div>
</template>

<style scoped lang="scss"></style>
