<script setup lang="ts">
import type { ChartData } from 'chart.js';
import { Bar } from 'vue-chartjs';
import { colors, gridColor, gridColorBold } from '@/types/graphs';
import type { Iteration } from '@/types/perceptron';

const props = defineProps<{
    iterations: Iteration[];
}>();

/**
 * Return the datasets of the iterations with the form { label: `Exemple ${exampleIndex}`, data: [error for iteration 1, error for iteration 2, ...] }
 */
function getPerceptronErrorsPerIteration(): ChartData<
    'bar',
    (number | [number, number] | null)[]
>[] {
    const datasets: ChartData<'bar', (number | [number, number] | null)[]>[] =
        [];
    const epochAverageError: number[] = [];

    const backgroundColors = colors;

    props.iterations.forEach((iteration) => {
        const exampleLabel = `Exemple ${iteration.exampleIndex}`;
        let dataset = datasets.find((d) => d.label === exampleLabel);
        if (!dataset) {
            dataset = {
                label: exampleLabel,
                data: [],
                order: 1,
                backgroundColor:
                    backgroundColors[
                        iteration.exampleIndex % backgroundColors.length
                    ],
            };
            datasets.push(dataset);
        }
        dataset.data.push(iteration.error);

        // Epoch error
        epochAverageError[iteration.epoch - 1] =
            (epochAverageError[iteration.epoch - 1] || 0) +
            iteration.error ** 2 / 2;
    });

    // Sort dataset by label (Exemple 0, Exemple 1, ...)
    datasets.sort((a, b) => {
        const aIndex = parseInt(a.label.split(' ')[1]);
        const bIndex = parseInt(b.label.split(' ')[1]);
        return aIndex - bIndex;
    });

    // Epoch error
    const epochErrorDataset = {
        type: 'line',
        label: "Erreur de l'époque",
        data: [],
        backgroundColor: '#fff',
        borderColor: '#fff',
        order: 0,
        tension: 0.3,
    };

    epochAverageError.forEach((error) => {
        epochErrorDataset.data.push(error);
    });

    datasets.push(epochErrorDataset);

    return datasets;
}
</script>

<template>
    <Bar
        class="flex"
        :options="{
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Nombre d\'erreurs par epoch',
                },
            },
            scales: {
                x: {
                    stacked: true,
                    min: 0,
                },
                y: {
                    stacked: true,
                    beginAtZero: true,
                    grid: {
                        color: function (context) {
                            if (context.tick.value == 0) {
                                return gridColorBold;
                            }

                            return gridColor;
                        },
                    },
                },
            },
        }"
        :data="{
            labels: props.iterations.reduce((labels, iteration) => {
                if (!labels.includes(`Époch ${iteration.epoch}`)) {
                    labels.push(`Époch ${iteration.epoch}`);
                }
                return labels;
            }, [] as string[]),
            datasets: getPerceptronErrorsPerIteration(),
        }"
    />
</template>
