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

function drawChart() {
    var options = {
    chart: {
        type: 'heatmap',
        height: 400,
        width: '100%',
        toolbar: {
        show: false
        }
    },
    title: {
        text: 'Confusion Matrix', // Title here
        align: 'center',
        style: {
            fontSize: '24px',
            fontWeight: 'bold',
            color: '#333'
        },
        margin: 50
    },
    yaxis: { // Changed from xaxis
        title: {
        text: 'Original Class'
        },
        labels: {
        rotate: -65
        },
             
        position: 'bottom',
    },
    xaxis: { // Changed from xaxis
        title: {
        text: 'Predicted Class'
        },
        labels: {
        rotate: -45
        },        
        position: 'bottom',
    },
    plotOptions: {
      heatmap: {
        colorScale: {
          ranges: [
            { from: 0, to: 10, color: '#54A3A8' },
            { from: 11, to: 20, color: '#546DA8' },
            { from: 21, to: 35, color: '#5589A9' },
            { from: 31, to: 40, color: '#54A892' },
            { from: 41, to: 50, color: '#5554A8' },
            { from: 51, to: 60, color: '#54A892' },
            { from: 61, to: 70, color: '#5488A8' },
          ]
        }
      }
    },
    dataLabels: {
      enabled: true,
    },
    tooltip: {
      enabled: false,
    },
    series: [],   
    
  };

  // Generate series data
  var seriesData = [];
  for (var i = 1; i <= 9; i++) {
    var rowData = [];
    for (var j = 1; j <= 9; j++) {
      rowData.push(Math.floor(Math.random() * 71)); // Generating random number between 0 and 70
    }
    seriesData.push({ name: `${i}`, data: rowData });
  }
  options.series = seriesData;

  var chart = new ApexCharts(document.querySelector("#ConfusionMatrix"), options);
  chart.render();

  // Update data every 2 seconds
  setInterval(function() {
    var newData = [];
    var deviceId = localStorage.getItem('deviceId');
    if (deviceId !== 'xAq9W1PO5rmAuuQ' && deviceId !== 'wzI0R1JqWqV0Lyi') {
      // If the device ID doesn't match, set all values to 0
      for (var i = 1; i <= 9; i++) {
        var rowData = [];
        for (var j = 1; j <= 9; j++) {
          rowData.push(0);
        }
        newData.push({ name: `${i}`, data: rowData });
      }
    } else {
      // If the device ID matches, generate random data
      for (var i = 1; i <= 9; i++) {
        var rowData = [];
        for (var j = 1; j <= 9; j++) {
          rowData.push(Math.floor(Math.random() * 71)); // Generating random number between 0 and 70
        }
        newData.push({ name: `${i}`, data: rowData });
      }
    }
    chart.updateSeries(newData);
  }, 2000);
}