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

    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(apiURL("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(apiURL("stats/daily"), {
            method: "GET",
            headers: {
                Authorization: `Bearer ${$token}`
            }
        });

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

    }

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

        if (res.ok) {
            const json = await res.json();
            let labels = json.map((d: any) => d.date);
            let data = json.map((d: any) => 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: any) {
        [lastSevenDays, lastSevenDaysData] = result;
        lineChart = new ChartJS(lineCanvasRef, {
            type: "line",
            data: {
                labels: lastSevenDays,
                datasets: [
                    {
                        label: "Totals",
                        data: lastSevenDaysData,
                        backgroundColor: "rgba(255, 192, 192, 0.2)"
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        suggestedMax: 30,
                        beginAtZero: true,
                        ticks: {
                            autoSkip: true,
                            stepSize: 5
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: "Weekly Breakdown"
                    },
                    subtitle: {
                        display: true,
                        text: "Water consumption over the last week",
                        padding: {bottom: 10}
                    }
                }
            }
        });
    }

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

        barChart = new ChartJS(barCanvasRef, {
            type: "bar",
            data: {
                labels: userTotalsLabels,
                datasets: [
                    {
                        data: userTotalsData,
                        backgroundColor: [
                            "#330000",
                            "rgba(100, 200, 192, 0.2)"
                        ]
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        suggestedMax: 10,
                        ticks: {
                            autoSkip: true,
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: "Daily Total"
                    },
                    subtitle: {
                        display: true,
                        text: "Water Drank Today",
                        padding: {bottom: 10}
                    }
                }
            }
        });
    }

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

    function updateDailyUserTotalsChart(result: any) {
        [, 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 --height="300px">
        <!--<Chart />-->
        <canvas bind:this={barCanvasRef} />
    </Card>
    <Card --height="300px">
        <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 /> -->
