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

    let json: Promise<any>;

    let barCanvasRef: HTMLCanvasElement;
    let lineCanvasRef: HTMLCanvasElement;
    let barChart: any;
    let lineChart: any;

    let lastSevenDays: string[];
    let lastSevenDaysData: number[];

    let userTotalsLabels: string[];
    let userTotalsData: number[];

    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");
        }
    }

    async function fetchDailyUserStatistics() {
        const res = await fetch("http://localhost:8080/api/v1/stats/totals/", {
            method: "GET",
            headers: {
                Authorization: `Bearer ${$token}`
            }
        });

        if (res.ok) {
            const json = await res.json();
            let labels = json.map(d => d.name);
            let data = json.map(d => d.total);
            return [labels, data];
        } else {
            throw new Error("There was a problem with your request");
        }

    }

    async function fetchWeeklyTotals() {
        const res = await fetch("http://localhost:8080/api/v1/stats/weekly/", {
            method: "GET",
            headers: {
                Authorization: `Bearer ${$token}`
            }
        });

        if (res.ok) {
            const json = await res.json();
            let labels = json.map(d => d.date);
            let data = json.map(d => d.total);
            return [labels, data];
        } else {
            throw new Error("There was a problem with your request");
        }
    }

    function closeDialog() {
        addFormOpen.set(false);
    }

    function onStatisticAdd() {
        closeDialog();
        fetchData();
        fetchWeeklyTotals().then(updateWeeklyTotalsChart).catch(err => console.error(err));
        fetchDailyUserStatistics().then(updateDailyUserTotalsChart).catch(err => console.error(err));
    }

    function setupWeeklyTotalsChart(result) {
        [lastSevenDays, lastSevenDaysData] = result;
        lineChart = new Chart(lineCanvasRef, {
            type: "line",
            data: {
                labels: lastSevenDays,
                datasets: [
                    {
                        label: "Totals",
                        data: lastSevenDaysData,
                        backgroundColor: "rgba(255, 192, 192, 0.2)"
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }

    function setupDailyUserTotalsChart(result) {
        [userTotalsLabels, userTotalsData] = result;

        barChart = new Chart(barCanvasRef, {
            type: "bar",
            data: {
                labels: userTotalsLabels,
                datasets: [
                    {
                        data: userTotalsData,
                        backgroundColor: [
                            "#330000",
                            "rgba(100, 200, 192, 0.2)"
                        ]
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }

    function updateWeeklyTotalsChart(result) {
        [,lastSevenDaysData] = result;
        lineChart.data.datasets[0].data = lastSevenDaysData;
        lineChart.update();
    }

    function updateDailyUserTotalsChart(result) {
        [,userTotalsData] = result;
        barChart.data.datasets[0].data = userTotalsData;
        barChart.update();
    }

    onMount(() => {
        fetchData();
        fetchWeeklyTotals().then(setupWeeklyTotalsChart);
        fetchDailyUserStatistics().then(setupDailyUserTotalsChart);
    });

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

<Column --width="500px">
    <Card>
        <canvas bind:this={barCanvasRef} width="" />
    </Card>
    <Card>
        <canvas bind:this={lineCanvasRef} />
    </Card>
</Column>

<AddForm open={$addFormOpen} on:submit={onStatisticAdd} on:close={closeDialog} />
<Column>
    <Card>
        {#await json then data}
            <Table {data} nofooter />
        {:catch error}
            <p>{error}</p>
        {/await}
    </Card>
</Column>
<!-- <Chart /> -->


<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>
