<script lang="ts">
	import {
		Chart,
		Title,
		Tooltip,
		Legend,
		BarElement,
		CategoryScale,
		LinearScale,
		BarController,
		Colors
	} from 'chart.js';
	import type { ModelStats } from './types';

	Chart.register(
		Title,
		Tooltip,
		Legend,
		BarElement,
		CategoryScale,
		LinearScale,
		BarController,
		Colors
	);

	let { data } = $props<{ data: ModelStats }>();

	let ctx: HTMLCanvasElement;

	let chart: Chart;

	$effect(() => {
		if (data && ctx) {
			if (chart) {
                console.log("update")
				chart.data = {
					labels: data.map((a) => a.name),
					datasets: [
						{
							label: 'Training',
							data: data.map((a) => a.training)
						},
						{
							label: 'Testing',
							data: data.map((a) => a.testing)
						}
					]
				};
				chart.update('resize');
			} else {
                console.log("create")
				chart = new Chart(ctx, {
					type: 'bar',
					data: {
						labels: data.map((a) => a.name),
						datasets: [
							{
								label: 'Training',
								data: data.map((a) => a.training)
							},
							{
								label: 'Testing',
								data: data.map((a) => a.testing)
							}
						]
					},
					options: {
						scales: {
							x: {
								stacked: true
							},
							y: {
								stacked: true
							}
						}
					}
				});
			}
		}
	});
</script>

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

<style lang="scss">
	canvas {
		width: 100%;
	}
</style>
