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

function drawChart() {
    var dataAttack = google.visualization.arrayToDataTable([
        ["Element", "Density", { role: "style" }],
        ["192.168.11.2", 0, "#2F4A8A"],
        ["192.168.14.3", 0, "#2F848A"],
        ["192.168.10.4", 0, "#504ED4"],
        ["192.168.1.5", 0, "#4ED4B0"],
        ["192.168.8.6", 0, "#54A3A8"],
        ["192.168.4.7", 0, "#546DA8"],
        ["192.168.12.8", 0, "#5589A9"],
        ["192.168.14.9", 0, "#4ECBD4"],
        ["192.168.16.10", 0, "#4E76D4"],
        ["192.168.1.11", 0, "#201EC7"],
        ["192.168.32.12", 0, "#4ED4B0"],
        ["192.168.17.13", 0, "#1EC79A"],
        ["192.168.16.14", 0, "#1D86C7"],
        ["192.168.10.15", 0, "#1E51C7"],
    ]);

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

    var options = {
        title: "Number of Attack request",
        bar: { groupWidth: "95%" },
        legend: { position: "none" },
        backgroundColor: '#0c212b',
        tooltip: { trigger: 'none' },
        hAxis: {           
            viewWindow: {
                min: 0,
                max: 500
            }
        },
    };
    var chartAttack = new google.visualization.BarChart(document.getElementById("barchart_attack"));

    function updateData() {
        var deviceId = localStorage.getItem('deviceId');
        if (deviceId === 'xAq9W1PO5rmAuuQ' || deviceId === 'wzI0R1JqWqV0Lyi') {
            for (var i = 0; i < dataAttack.getNumberOfRows(); i++) {
                dataAttack.setValue(i, 1, Math.floor(Math.random() * 20)); // Random value
            }
        } else {
            for (var i = 0; i < dataAttack.getNumberOfRows(); i++) {
                dataAttack.setValue(i, 1, 0);
            }
        }
        chartAttack.draw(view, options);
    }

    // Initial draw
    updateData();

    // Update data every 2 seconds
    setInterval(updateData, 2000);
}
