<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>
                <div class="text-h6 q-mt-md">Online Game</div>

                <div class="text-subtitle2 text-black">
                    Game ID: {{ gameID }}
                </div>
            </q-card-section>

            <q-separator />

            <q-card-section>
                <div class="text-h6 q-mt-md">Players:</div>
                
                <li v-for="plr in gamePlayers" :key="plr.username">
                    <div class="text-subtitle2 text-black">{{ plr.username }}</div>
                </li>
            </q-card-section>

            <q-separator />

            <q-card-actions align="center">
              <q-btn
                    v-if="gameCreator === user.id"
                    label="Start Game!"
                    color="primary"
                    @click="startGame"
                    rounded
                    unelevated
                    size="lg"
                    class="full-width"
              />
            </q-card-actions>
        </q-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted  } 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(null);
const gameCreator = ref(null);
const gamePlayers = ref([]);
const user = ref({ username:"", id:0 });
var canUpdate = false

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

const storedgameID = LocalStorage.getItem("gameID")
if (storedgameID) {
    console.log(storedgameID)
    gameID.value = storedgameID

    api.get(`/api/games/${gameID.value}`)

    .then(function (response) {
        console.log(response);

        gameCreator.value = response.data.creator

        canUpdate = true
    })

    .catch(function (error) {
        console.log(error);

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

} else {
    router.push("/")
}

async function update() {
    if (!canUpdate) {return}

    api.get(`/api/games/${gameID.value}/players`)

    .then(function (response) {
        gamePlayers.value = response.data
    })
    
    .catch(function (error) {
        console.log(error);

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

    api.get(`/api/games/${gameID.value}`)

    .then(function (response) {
        if (!response.data.is_open) {
            router.push("/game")
        }
    })
    
    .catch(function (error) {
        console.log(error);

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

async function startGame() {

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

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

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

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

let intervalId = null

onMounted(() => {
    update()

    intervalId = setInterval(update, 1000)
})

onUnmounted(() => {
    clearInterval(intervalId)
})

</script>
