pHChartColor = "#E91E63";
tempChartColor = "#1F456E";
salinityChartColor = "#7877FF";
conductivityChartColor = "#252A34";

const xValues = []
const yValues = [];
var dragOptions = {
  animationDuration: 1000
};

const zoomConfig = {
  zoom: {
    enabled: true,
    drag: dragOptions,
    mode: 'xy',
    speed: 0.05,
    onZoom: function () {
        leftEnd = pHChart.options.scales.xAxes[0].ticks.min;
        rightEnd = pHChart.options.scales.xAxes[0].ticks.max;
        updateZoom(leftEnd, rightEnd);
    }
  }
};

//const xAxisConfig = [{type: 'time', time: { displayFormats: { second: 'D MMM H:mm', minute: 'D MMM H:mm' }}}];
const xAxisConfig = [{
  type: 'time',
  time: {
    displayFormats: {
      second: 'HH:mm',
      minute: 'HH:mm',
      hour: 'HH:mm'
    }
  },
  ticks: {
    autoSkip: true,
    maxTicksLimit: 8, // Show at most 8 labels
    maxRotation: 0, // No rotation
    minRotation: 0
  }
}];

var chartLimits = {
    annotations: [{
        drawTime: 'beforeDatasetsDraw',
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: null,
        borderColor: 'green',
        borderWidth: 2,
        borderDash: [2, 2],
    },{
      drawTime: 'beforeDatasetsDraw',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: null,
      borderColor: 'green',
      borderWidth: 2,
      borderDash: [2, 2],
  }]
};

function getChartLimits( metric )
{
  chartLimits.annotations[0].value = localStorage.getItem( metric+"Lower" );
  chartLimits.annotations[1].value = localStorage.getItem( metric+"Upper" );
  return chartLimits;
}

function updateZoom(leftEnd, rightEnd) {
  Chart.helpers.each(Chart.instances, function (instance) {
      instance.options.scales.xAxes[0].ticks.min = leftEnd;
      instance.options.scales.xAxes[0].ticks.max = rightEnd;              
      instance.update();
  });
}

function updatePointRadius(chart, threshold = 100) {
    if (!chart) return;
    const numPoints = chart.data.labels.length;
    chart.data.datasets.forEach(ds => {
        ds.pointRadius = numPoints > threshold ? 0 : 3; // 3 is default, or set as you like
    });
    chart.update();
}

var pHChart = null;
function initPHChart() {
  // Destroy previous chart if it exists
  if (pHChart) {
    pHChart.destroy();
  }
  const ctx = document.getElementById("pHChart").getContext("2d");
  pHChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xValues,
      datasets: [{
        label: 'pH',
        fill: false,
        tension: 0.1,
        backgroundColor: pHChartColor,
        borderColor: pHChartColor,
        data: yValues
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {display: false},
      scales: {
        xAxes: xAxisConfig,
        yAxes: [{ ticks: { min: 0, max: 14 } }]
      },
      plugins: {
        zoom: zoomConfig,
      },
      annotation: getChartLimits("ph"),
    }
  });
}

var tempChart = null;
function initTempChart() {
  // Destroy previous chart if it exists
  if (tempChart) {
    tempChart.destroy();
  }
  const ctx = document.getElementById("tempChart").getContext("2d");
  tempChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xValues,
      datasets: [{
        label: 'Temperature °C',
        fill: false,
        tension: 0.1,
        backgroundColor: tempChartColor,
        borderColor: tempChartColor,
        data: yValues
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {display: false},
      scales: {
        xAxes: xAxisConfig,
        yAxes: [{ ticks: { min: 0, max: 30 } }]
      },
      annotation: getChartLimits("temp"),
    }
  });
}

var salinityChart = null;
function initSalinityChart() {
  // Destroy previous chart if it exists
  if (salinityChart) {
    salinityChart.destroy();
  }
  const ctx = document.getElementById("salinityChart").getContext("2d");
  salinityChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xValues,
      datasets: [{
        label: 'Salinity',
        fill: false,
        tension: 0.1,
        backgroundColor: salinityChartColor,
        borderColor: salinityChartColor,
        data: yValues
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {display: false},
      scales: {
        xAxes: xAxisConfig,
        yAxes: [{ ticks: { min: 0 } }]
      },
      annotation: getChartLimits("salinity"),
    }
  });
}

var conductivityChart = null;
function initConductivityChart() {
  // Destroy previous chart if it exists
  if (conductivityChart) {
    conductivityChart.destroy();
  }
  const ctx = document.getElementById("conductivityChart").getContext("2d");
  conductivityChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xValues,
      datasets: [{
        label: 'Conductivity',
        fill: false,
        tension: 0.1,
        backgroundColor: conductivityChartColor,
        borderColor: conductivityChartColor,
        data: yValues
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {display: false},
      scales: {
        xAxes: xAxisConfig,
        yAxes: [{ ticks: { min: 0 } }]
      },
      annotation: getChartLimits("conductivity"),
    }
  });
}

function addData(chart, label, data) {
  chart.data.labels.push(label);
  chart.data.datasets.forEach((dataset) => {
      dataset.data.push(data);
  });
  chart.update();
}

function createCsvDownloadLink(csvData) 
{
  // Create a Blob from the CSV data
  const blob = new Blob([csvData], { type: 'text/csv' });

  // Create a temporary URL for the Blob
  const blobUrl = URL.createObjectURL(blob);

  // Create a download link element
  const downloadLink = document.createElement('a');
  downloadLink.href = blobUrl;
  downloadLink.download = 'data.csv'; // Specify the filename

  // Add the link to the document
  document.body.appendChild(downloadLink);

  // Simulate a click on the link to trigger the download
  downloadLink.click();

  // Clean up by revoking the Blob URL
  URL.revokeObjectURL(blobUrl);
}

function celsius_to_fahrenheit(celsius)
{
  fahrenheit = celsius * 9/5 + 32;
  return fahrenheit
}

function padZero(number) {
  return number < 10 ? '0' + number : number;
}