<script lang="ts">
    import {onMount} from "svelte"
    import {
        Chart,
        LineController,
        LineElement,
        PointElement,
        LinearScale,
        TimeScale,
        Tooltip,
        Legend,
        Title
    } from "chart.js"
    import type {FightStats} from "./types/stats.ts"
    import 'chartjs-adapter-moment'

    export let data: FightStats;
    let chart;
    let canvas: HTMLCanvasElement;

    onMount(async () => {
        Chart.register(LineController, LineElement, PointElement, LinearScale, TimeScale, Tooltip, Legend, Title)
        if (document.body.parentElement!.classList.contains("dark")) {
            Chart.defaults.color = "#fff"
        }

        const colors = ["#abfa91", "#279900", "#00ffbe", "#9297fb", "#050b9d", "#b60fff", "#8dddfc", "#0880ad", "#41ff00", "#039973", "#96fce2", "#0009ff", "#7501a4", "#e2a2fb", "#00b9ff"];
        const map = new Map<string, {x: Date, y: number}[]>()
        for (const {date, count, gamemode} of data) {
            if (!map.has(gamemode)) {
                map.set(gamemode, [])
            }
            map.get(gamemode)!!.push({x: new Date(date), y: count})
        }

        chart = new Chart(
            canvas,
            {
                type: "line",
                data: {
                    datasets: Array.from(map.entries()).map(([gamemode, data]) => {
                        const color = colors.pop()
                        return {
                            label: gamemode,
                            fill: false,
                            borderColor: color,
                            backgroundColor: color,
                            spanGaps: true,
                            data
                        };
                    })
                },
                options: {
                    scales: {
                        x: {
                            type: "time",
                            time: {
                                unit: "day"
                            }
                        },
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            }
        )
    })
</script>

<div>
    <canvas bind:this={canvas} />
</div>