const thermocoupleTypeTable = ["uV", "B", "E", "J", "K", "N", "R", "S", "T"];

const elements = {
  read: {
    vdd: document.getElementById("vdd"),
    vref: document.getElementById("vref"),
    vadj: document.getElementById("vadj"),
    ts: document.getElementById("timestamp"),
    table: document.getElementById("data"),
  },
  config: {
    table: document.getElementById("thermocouple"),
  },
};

let readOldChannelCount = 0;
let configOldChannelCount = 0;

async function fetchData(url) {
  const response = await fetch(url);
  return response.json();
}

function clearTableBody(tableType) {
  const table = elements[tableType].table;
  const tbody = table.querySelector("tbody");

  if (tbody) {
    tbody.innerHTML = "";
  } else {
    // If tbody doesn't exist, recreate it
    const newTbody = document.createElement("tbody");
    table.appendChild(newTbody);
  }
}

function updateTable(data, tableType, oldChannelCount, updateFunction) {
  clearTableBody(tableType);

  oldChannelCount = 0;

  data.channels.forEach((channel) => {
    updateFunction(channel, tableType);
    oldChannelCount++;
  });
}

function updateReadTable(channel, tableType) {
  const { value, id } = channel;

  const row = elements[tableType].table.querySelector("tbody").insertRow(-1);
  row.insertCell(0).innerText = id;
  row.insertCell(1).innerText = value.toFixed(2);
}

function updateConfigTable(channel, tableType) {
  const { id, thermocouple, gain, offset, filter } = channel;

  const row = elements[tableType].table.querySelector("tbody").insertRow(-1);
  row.insertCell(0).innerText = id;
  row.insertCell(1).innerText = thermocoupleTypeTable[thermocouple];
  row.insertCell(2).innerText = gain;
  row.insertCell(3).innerText = offset;
  row.insertCell(4).innerText = filter.sample_size;
  row.insertCell(5).innerText = filter.type;
}

function updateOthers(data) {
  const { ratio, time } = data;
  elements.read.ts.innerText = time;
  elements.read.vref.innerHTML = `V<sub>REF</sub>: ${ratio.vref}`;
  elements.read.vadj.innerHTML = `V<sub>ADJ</sub>: ${ratio.vadj.toFixed(4)}`;
  elements.read.vdd.innerHTML = `V<sub>DD</sub>: ${ratio.pivdd.toFixed(4)}`;
}

async function updateRead() {
  const data = await fetchData("/data");
  updateTable(data, "read", readOldChannelCount, updateReadTable);
  updateOthers(data);
}

async function updateConfig() {
  const data = await fetchData("/config");
  updateTable(data.config, "config", configOldChannelCount, updateConfigTable);
}

updateRead();
updateConfig();

setInterval(updateRead, 1000);
setInterval(updateConfig, 5000);