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

let chart; // Declare the chart variable globally

function drawChart() {
  var options = {
    chart: {
      type: 'line',
      height: 400,
      toolbar: {
        show: false
      }
    },
    vAxis: {
      viewWindow: {
        min: 0,
        max: 100
      }
    },
    dataLabels: {
      enabled: false,
    },
    tooltip: {
      enabled: false,
    },
    xaxis: {
      title: {
        text: "Alpha i's"
      },
      labels: {
        rotate: -45
      }
    },
    yaxis: {
      title: {
        text: 'Error measure'
      },
      position: 'right',
      offsetY: 20,
      axisBorder: {
        show: true,
      },
      axisTicks: {
        show: true,
      },
      min: 0,
      max: 100
    },
    series: [{
      name: 'Series 1',
      data: generateRandomData()
    }],
    xaxis: {
      categories: ['2', '4', '6', '8', '10', '12']
    }
  };

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

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

function generateRandomData() {
  var newData = [];
  var deviceId = localStorage.getItem('deviceId');

  if (deviceId !== 'xAq9W1PO5rmAuuQ' && deviceId !== 'wzI0R1JqWqV0Lyi') {
    for (var i = 0; i < 6; i++) {
      newData.push(0); // Set value to 0
    }
  } else {
    for (var i = 0; i < 6; i++) {
      newData.push(Math.floor(Math.random() * 9)); // Generate random number between 0 and 8
    }
  }

  return newData;
}

function updateChartData() {
  var deviceId = localStorage.getItem('deviceId');

  if (deviceId !== 'xAq9W1PO5rmAuuQ' && deviceId !== 'wzI0R1JqWqV0Lyi') {
    chart.updateSeries([{
      data: [0, 0, 0, 0, 0, 0]
    }]);
  } else {
    chart.updateSeries([{
      data: generateRandomData()
    }]);
  }
}