<script setup>
import { request } from "../assets/helpers.js";
import { useStore } from "vuex";
import { ref, watch } from "vue";

const userStore = useStore("userStore");
const childrenList = ref(null);
const error = ref("");

watch(userStore.state, async () => {
	if (userStore.state.userInfo?.isParent) {
		childrenList.value = await request("GET", "/children");
	}
});

async function dispense() {
	await request("POST", "/dispense");
	userStore.state.userInfo.dispenses--;
}
async function saveChild(child) {
	await request("PUT", "/children/" + child.id + "/dispenses", {dispenses: child.dispenses})
		.then(() => error.value = "")
		.catch(err => error.value = err);
}
</script>

<template>
	<main>
		<template v-if="userStore.state.userInfo">
			<h2>Welcome back, {{ userStore.state.userInfo.username }}</h2>
			<br>
			<h3 v-show="!userStore.state.userInfo.isParent">You have {{ userStore.state.userInfo.dispenses }} dispenses remaining</h3>
			<br>
			<button @click="dispense" :disabled="userStore.state.userInfo.dispenses === 0 && !userStore.state.userInfo.isParent">Dispense the m&m</button>
			<br><br>
			<h3>Your touch code is: {{ userStore.state.userInfo.touchCode }}</h3>
			<p>Use this code to login on the dispenser</p>
			<br>

			<template v-if="userStore.state.userInfo.isParent">
				<h2>Users:</h2>
				<br>
				<table align="center">
					<tr>
						<th>Username</th>
						<th>Dispenses</th>
					</tr>
					<tr v-for="child in childrenList">
						<td>{{ child.username }}</td>
						<td>
							<input type="number" min="0" v-model="child.dispenses" style="background: inherit; border: none; color: inherit; font-family: inherit">
							<button style="padding: 2px" @click="saveChild(child)">Save</button>
						</td>
					</tr>
				</table>
			</template>

			<br>
			<p class="error">{{ error }}</p>
		</template>

		<template v-else>
			<h1>M&M Dispenser</h1>

			<p>Please login to continue</p>
		</template>
	</main>
</template>

