<script>
    import { fetchMetrics } from "../api/metrics.ts";
    import { onMount } from "svelte";
    import { Chart, registerables } from "chart.js";
    Chart.register(...registerables);

    let canvas;
    onMount(async () => {
        const ctx = canvas.getContext("2d");
        const { labels, datasets } = await fetchAndPrepareMetrics();

        var c = new Chart(ctx, {
            type: "line",
            data: { labels, datasets },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: `Top Requests`,
                },
                scales: {
                    y: {
                        stacked: true,
                    },
                },
            },
        });
    });

    const fetchAndPrepareMetrics = async () => {
        const { error, payload } = await fetchMetrics({ key: "clientIp" });
        if (error) {
            return {};
        }

        const chartData = payload.reduce((agg, x) => {
            let root = agg[x.Header] || {
                labels: [],
                dataset: {
                    label: x.Header,
                    borderColor: "rgb(75,192,192)",
                    data: [],
                },
            };
            root.dataset.data = root.dataset.data.concat(x.Count);
            root.labels = root.labels.concat(x.Time);
            agg[x.Header] = root;
            return agg;
        }, {});

        const finalChartData = Object.keys(chartData).map((x) => chartData[x]);
        const finalChartLabels = finalChartData[0].labels;

        return {
            labels: finalChartLabels,
            datasets: finalChartData.map((x) => x.dataset),
        };
    };
</script>

<div style="position: relative; max-height: 512px; height: 512px; width: 100%;">
    <canvas width="100%" height="100%" bind:this={canvas} />
</div>
