google.charts.load("current", { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    function fetchDataAndDrawChart() {
        // Fetch data from Django view
        fetch('/read_tx_bytes')
            .then(response => response.json())
            .then(data => {
                // Check device ID
                var deviceId = localStorage.getItem('deviceId');
                if (deviceId === 'xAq9W1PO5rmAuuQ' || deviceId === 'wzI0R1JqWqV0Lyi') {
                    // Create data array from the response
                    const chartData = [["Density", "Element", { role: "style" }]];
                    data.tx_kbps_data.forEach((value, index) => {
                        chartData.push([`${index + 1}`, parseFloat(value), "#1D86C7"]);
                    });

                    // Create DataTable from the data array
                    const dataTable = google.visualization.arrayToDataTable(chartData);
                    var view = new google.visualization.DataView(dataTable);
                    view.setColumns([0, 1, 2]);

                    var options = {
                        title: "TX_KBPS",
                        bar: { groupWidth: "95%" },
                        legend: { position: "none" },
                        backgroundColor: '#0c212b',
                        tooltip: { trigger: 'none' }
                    };

                    var chart = new google.visualization.ColumnChart(document.getElementById("TransmittedBytesChart"));
                    chart.draw(view, options);
                } else {
                    // Draw chart with zero values
                    const chartData = [["Density", "Element", { role: "style" }]];
                    for (let i = 1; i <= 8; i++) {
                        chartData.push([`${i}`, 0, "#1D86C7"]);
                    }

                    const dataTable = google.visualization.arrayToDataTable(chartData);
                    var view = new google.visualization.DataView(dataTable);
                    view.setColumns([0, 1, 2]);

                    var options = {
                        title: "TX_KBPC",
                        bar: { groupWidth: "95%" },
                        legend: { position: "none" },
                        backgroundColor: '#0c212b',
                        tooltip: { trigger: 'none' }
                    };

                    var chart = new google.visualization.ColumnChart(document.getElementById("TransmittedBytesChart"));
                    chart.draw(view, options);
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                // If error occurs, draw the chart with zero values
                const chartData = [["Density", "Element", { role: "style" }]];
                for (let i = 1; i <= 8; i++) {
                    chartData.push([`${i}`, 0, "#1D86C7"]);
                }

                const dataTable = google.visualization.arrayToDataTable(chartData);
                var view = new google.visualization.DataView(dataTable);
                view.setColumns([0, 1, 2]);

                var options = {
                    title: "TX_KBPC",
                    bar: { groupWidth: "95%" },
                    legend: { position: "none" },
                    backgroundColor: '#0c212b',
                    tooltip: { trigger: 'none' }
                };

                var chart = new google.visualization.ColumnChart(document.getElementById("TransmittedBytesChart"));
                chart.draw(view, options);
            });
    }

    // Call the function once to draw the initial chart
    fetchDataAndDrawChart();

    // Update chart every 5 seconds
    setInterval(fetchDataAndDrawChart, 5000);
    $(document).on('click', function() {
        fetchDataAndDrawChart();
    });
}
