var ctx = document.getElementById('barChart').getContext('2d');

var initialData = {
    labels: ['unknown', 'Not revealed', 'REEvil', 'WannaCry', 'Maze', 'Clop', 'Conti', 'Darkside'],
    datasets: [{
        label: 'Data',
        data: [2, 2, 2, 2, 2, 2, 2, 2],
        backgroundColor: [
            'rgba(255, 165, 0, 0.5)', // orange
            'rgba(255, 0, 0, 0.5)',   // red
            'rgba(255, 192, 203, 0.5)', // pink
            'rgba(0, 0, 255, 0.5)',   // blue
            'rgba(0, 255, 255, 0.5)', // aqua
            'rgba(238, 130, 238, 0.5)', // violet
            'rgba(192, 192, 192, 0.5)', // silver
            'rgba(0, 0, 0, 0.5)'       // black
        ],
        borderColor: [
            'rgba(255, 165, 0, 1)', // orange
            'rgba(255, 0, 0, 1)',   // red
            'rgba(255, 192, 203, 1)', // pink
            'rgba(0, 0, 255, 1)',   // blue
            'rgba(0, 255, 255, 1)', // aqua
            'rgba(238, 130, 238, 1)', // violet
            'rgba(192, 192, 192, 1)', // silver
            'rgba(0, 0, 0, 1)'       // black
        ],
        borderWidth: 1
    }]
};

var options = {
    scales: {
        y: {
            beginAtZero: false,
            min: 1,
            max: 100,          
            stepSize: 10
        }
    }
};

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: initialData,
    options: options
});

function updateChartData(newData) {
    myBarChart.data.datasets[0].data = newData;
    myBarChart.update();
}

function fetchDataAndUpdateChart() {
    var deviceId = localStorage.getItem('deviceId');
    var logDataEndpoint;
    if (deviceId === 'xAq9W1PO5rmAuuQ') {
        logDataEndpoint = '/log-data/';
    } else if (deviceId === 'wzI0R1JqWqV0Lyi') {
        logDataEndpoint = '/log-data1/';
    } else {
        // Device ID doesn't match, set all values to 2 and clear old data
        updateChartData([2, 2, 2, 2, 2, 2, 2, 2]);
        $('#detect-log').empty(); // Clear old data
        return;
    }
    
    $.get(logDataEndpoint, function (logData) {
        if (logData.trim() !== '') {                     
            $('#detect-log').html(logData);
            $('#change-button').show();                
            updateChartData([5, 100, 2, 2, 2, 2, 2, 2]);
        } else {
            $('#detect-log').html('No threat detected');
            $('#change-button').hide();
            var output = document.getElementById("output");
            output.style.display = "none";
            updateChartData([2, 2, 2, 2, 2, 2, 2, 2]);
        }				
    });
}

setInterval(fetchDataAndUpdateChart, 1000);
