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

function drawChart() {
    function getRandomData() {
        var data = [["Element", "Density", { role: "style" }]];
        for (var i = 0; i < 14; i++) {
            var value = Math.floor(Math.random() * 4) + 5; // Random value between 5 and 8
            data.push(["192.168.0." + (i + 2), value * 1, "#1E51C7"]);
        }
        return data;
    }

    function drawDynamicChart() {
        var deviceId = localStorage.getItem('deviceId');
        var data = google.visualization.arrayToDataTable(deviceId === 'xAq9W1PO5rmAuuQ' || deviceId === 'wzI0R1JqWqV0Lyi'? getRandomData() : getDefaultData());

        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1,
            {
                calc: "stringify",
                sourceColumn: 1,
                type: "string",
                role: "annotation"
            },
            2]);

        var options = {
            title: "Number of all incoming request",
            bar: { groupWidth: "95%" },
            legend: { position: "none" },
            backgroundColor: '#0c212b',
            tooltip: { trigger: 'none' },
            hAxis: {              
                viewWindow: {
                    min: 0,
                    max: 100
                }
            },
        };
        var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
        chart.draw(view, options);
    }

    function getDefaultData() {
        var data = [["Element", "Density", { role: "style" }]];
        for (var i = 0; i < 14; i++) {
            data.push(["10.0.0." + (i + 2), 0, "#1E51C7"]); // Set all values to 0
        }
        return data;
    }

    // Initial draw
    drawDynamicChart();

    // Update chart every second
    setInterval(function () {
        drawDynamicChart();
    }, 1000);
    $(document).on('click', function() {
        drawDynamicChart();
    });
}
