<template>
    <Pie :chart-data="chartData" :chart-options="chartOptions" :plugins="plugins" />
</template>

<script>
    import { Pie } from "vue-chartjs/legacy";
    import {
        Chart as ChartJS,
        Title, Tooltip, Legend,
        ArcElement, CategoryScale
    } from "chart.js";

    ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale);

    /**
     * Plugin inline (sans dependance) : ecrit le pourcentage au centre de
     * chaque quartier du camembert.
     */
    const percentLabels = {
        id: "percentLabels",
        afterDatasetsDraw: function (chart) {
            const ctx = chart.ctx;
            chart.data.datasets.forEach(function (dataset, datasetIndex) {
                const meta = chart.getDatasetMeta(datasetIndex);
                if (meta.hidden) {
                    return;
                }
                const total = dataset.data.reduce(function (sum, v) {
                    return sum + (v || 0);
                }, 0);
                if (!total) {
                    return;
                }
                meta.data.forEach(function (arc, i) {
                    const value = dataset.data[i] || 0;
                    const percent = Math.round((value / total) * 100);
                    if (percent < 4) {
                        return;
                    }
                    const pos = arc.tooltipPosition();
                    const text = percent + "%";
                    ctx.save();
                    ctx.font = "bold 12px sans-serif";
                    ctx.textAlign = "center";
                    ctx.textBaseline = "middle";
                    // Contour sombre + texte blanc : lisible sur toute couleur.
                    ctx.lineWidth = 3;
                    ctx.strokeStyle = "rgba(0, 0, 0, 0.45)";
                    ctx.strokeText(text, pos.x, pos.y);
                    ctx.fillStyle = "#fff";
                    ctx.fillText(text, pos.x, pos.y);
                    ctx.restore();
                });
            });
        }
    };

    export default {
        name: "PieChart",

        components: { Pie },

        props: {
            /** Donnees au format Chart.js : { labels, datasets }. */
            chartData:    { type: Object, required: true },
            /** Options Chart.js passees par le parent. */
            chartOptions: { type: Object, default: () => ({}) }
        },

        data: function () {
            return {
                plugins: [percentLabels]
            };
        }
    };
</script>
