<script>
    import { onMount, createEventDispatcher } from "svelte";
    import Chart from 'chart.js/auto';
    import ChartDataLabels from 'chartjs-plugin-datalabels';
    import { getCountRutasBuses } from "$/services/lineas";
    import { getCount } from "$/services/lineas";

    const dispatch = createEventDispatcher();
    let rutasConGPS = [];
    let rutasSinGPS = 0;
    let chart = null;

    onMount(() => { 
        dispatch('loading', true);

        Promise.all([
            getCountRutasBuses(),
            getCount({ vigente: 1 })
        ]).then(([dataRutasConGPS, dataTotalRutas]) => {
            rutasConGPS = dataRutasConGPS;
            rutasSinGPS = parseInt (dataTotalRutas.count) - parseInt (dataRutasConGPS.count);    
            updateChart();
        }).catch(error => {
            console.error('Error fetching counts:', error);
        }).finally(() => {
            dispatch('loading', false);
        });
    });

    function updateChart() {
        const ctx = document.getElementById('barChartR').getContext('2d');
        if (chart) {
            chart.destroy();
        }
        chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Rutas con información', 'Rutas sin información'],
                datasets: [{
                    label: 'Posicionamiento',
                    data: [rutasConGPS.count, rutasSinGPS],
                    backgroundColor: ['rgba(54, 162, 235, 0.8)', 'rgba(255, 99, 132, 0.8)']
                }]
            },
            plugins: [ChartDataLabels],
            options: {
                plugins: {
                    legend: {
                        display: true
                    },
                    tooltip: {
                        enabled: true
                    }
                },
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
</script>

<div class="card">
    <div class="card-body">
        <h5 class="card-title">Rutas con Informacion de Posicionamiento</h5>
        <canvas id="barChartR"></canvas>
    </div>
</div>
