<script lang='ts'>
    import { createEventDispatcher } from "svelte";
    import { token, user } from "../../stores/auth";
    import type { Statistic } from "../../types";
    import { apiURL } from "../../utils";

    export let open: boolean;

    const dispatch = createEventDispatcher();

    const statistic: Statistic = newStatistic();

    function newStatistic(): Statistic {
        let date = new Date().toString();

        return {
            user_id: $user!.id,
            date,
            quantity: 1
        };
    }

    function closeDialog() {
        dispatch("close");
    }

    async function handleSubmitStat()
    {
        const { user_id, date, quantity } = statistic;
        await fetch(apiURL("stats"), {
            method: "POST",
            headers: {
                Authorization: `Bearer ${$token}`
            },
            body: JSON.stringify({
                date: new Date(date),
                user_id,
                quantity
            })
        });
        dispatch("submit");
    }

</script>

<dialog id="addForm" {open} on:submit={handleSubmitStat}>
    <h2>Add Water</h2>
    <form method="dialog">
        <div class="form input group">
            <label for="date">Date:</label>
            <input bind:value={statistic.date} id="date" name="date" type="datetime-local" />
        </div>
        <div class="form input group">
            <label for="quantity">Quantity:</label>
            <input
                bind:value={statistic.quantity}
                id="quantity"
                name="quantity"
                type="number"
                min="0"
                autocomplete="off"
            />
        </div>
        <button on:click={closeDialog}>Cancel</button>
        <button type="submit">Submit</button>
    </form>
</dialog>
