<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import { token } from "../stores/auth";
    import Table from "./Table.svelte";
    import Chart from "chart.js/auto";
    import AddForm from "./forms/AddForm.svelte";

    let open: boolean = false;

    let json: Promise<any>;

    let canvasRef: HTMLCanvasElement;
    let chart: any;

    let lastSevenDays: string[];

    async function fetchData() {
        const res = await fetch("http://localhost:8080/api/v1/stats/", {
            method: "GET",
            headers: {
                Authorization: `Bearer ${$token}`
            }
        });
        if (res.ok) {
            json = res.json();
        } else {
            throw new Error("There was a problem with your request");
        }
    }

    function getLastSevenDays() {
        const result = [];
        for (let i = 0; i < 7; i++) {
            let d = new Date();
            d.setDate(d.getDate() - i);
            result.push(d.toISOString().substring(0, 10));
        }
        return result;
    }

    function handleClick() {
        open = true;
    }

    function closeDialog() {
        open = false;
    }

    function onStatisticAdd() {
        open = false;
        fetchData();
    }

    onMount(() => {
        fetchData();
        lastSevenDays = getLastSevenDays();
        chart = new Chart(canvasRef, {
            type: "bar",
            data: {
                labels: lastSevenDays,
                datasets: [
                    {
                        label: "Zach",
                        data: [1, 2, 8, 2, 5, 5, 1],
                        backgroundColor: "rgba(255, 192, 192, 0.2)",
                        borderColor: "rgba(75, 192, 192, 1)",
                        borderWidth: 1
                    }, {
                        label: "Parker",
                        data: [6, 1, 1, 4, 3, 5, 1],
                        backgroundColor: "rgba(75, 192, 192, 0.2)",
                        borderColor: "rgba(75, 192, 192, 1)",
                        borderWidth: 1
                    }
                ]
            }
        });
    });

    onDestroy(() => {
        if (chart) chart.destroy();
        chart = null;
    });
</script>

<div>
    <button on:click={handleClick}>Add</button>
    <AddForm {open} on:submit={onStatisticAdd} on:close={closeDialog} />
    <canvas bind:this={canvasRef} />
    {#await json then data}
        <Table {data} nofooter />
    {:catch error}
        <p>{error}</p>
    {/await}
    <!-- <Chart /> -->
</div>

<style>
    dialog {
        background: red;
        box-shadow: 0 20px 5em 10px rgba(0, 0, 0, 0.8);
    }

    dialog::backdrop {
        padding: 20px;
        box-shadow: 20px 20px rgba(0, 0, 0, 0.8);
        background-color: red;
    }
</style>
