<script lang="ts">
import { onDestroy } from "svelte";
import ChartJS from "chart.js/auto";

export let data;
export let labels;
export let type = 'bar';

let ref: HTMLCanvasElement;
let chart

function setupChart(result) {
    [labels, data] = result;
    chart = new ChartJS(ref, {
        type,
        data: {
            labels,
            datasets: [
                {
                    label: "Totals",
                    data,
                    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}
                }
            }
        }
    });
    
    onDestroy(() => {
        if (chart) chart.destroy();
        chart = null;
    })
}
</script>

<canvas bind:this={ref} />