<template>
    <div class="q-pa-md flex flex-center">
        <q-card
            class="q-pa-lg shadow-3"
            style="width: 400px; max-width: 90vw; border-radius: 16px;"
        >

            <q-card-section class="text-center">
                <div class="text-h6 q-mt-md">Enter Game ID</div>
            </q-card-section>

            <q-card-section>
                <q-input
                    v-model="gameID"
                    filled
                    label="Game ID"
                    type="number"
                    dense
                    style="border-radius: 6px;"
                >
                  <template #prepend>
                    <q-icon name="public" />
                  </template>
                </q-input>
            </q-card-section>

            <q-card-actions align="center">
                <q-btn
                    label="Go!"
                    color="primary"
                    @click="joinGame"
                    rounded
                    unelevated
                    size="lg"
                    class="full-width"
                />
            </q-card-actions>
        </q-card>
    </div>
</template>

<script setup>
import { ref } from "vue";
import { useQuasar, LocalStorage } from "quasar";
import { api } from 'src/boot/axios';
import { useRouter } from 'vue-router'

const router = useRouter()
const $q = useQuasar();
const gameID = ref();
const user = ref({ username:"", id:0 });

const storedUser = LocalStorage.getItem("user")
if (storedUser) {
    console.log(storedUser)
    user.value = storedUser
} else {
    router.push("/user/username")
}

async function joinGame() {
    if (!gameID.value) {
        $q.notify({
            type: "negative",
            message: "Please enter a Game ID!",
        });
        return;
    }

    api.post(`/api/games/${gameID.value}/players`, {
      user: user.value.id
    })
    
    .then(function (response) {
        console.log(response);

        LocalStorage.setItem("gameID", gameID.value)

        $q.notify({
            type: "positive",
            message: "Success!",
        });

        router.push("/game/online/create")
    })
    
    .catch(function (error) {
      console.log(error);

      $q.notify({
        type: "negative",
        message: error.response.data.error,
      });
    });
}
</script>
