// Description: Main JavaScript file for the web application.
// arrays and stuff
const sensorData = {};
let liveGraphs = [];
let nodeArray = [];
let nodeDict = {};

const socket = new WebSocket("ws://145.92.8.114/ws");
function openConnection() {
  // Open connection
  socket.addEventListener("open", (event) => {
    console.log("Connected to the WebSocket server");
  });

  // Error handling
  socket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
    // Attempt to reconnect
    setTimeout(openConnection, 1000); // Retry after 1 second
  });

  // Message handling
  socket.addEventListener("message", (event) => {
    try {
      const jsonData = JSON.parse(event.data);
      // Use the parsed JSON data as needed
      handleIncomingData(jsonData);
      console.log(jsonData);

  } catch (error) {
      console.error("Error parsing JSON:", error);
  }
  });

  // Close handling
  socket.addEventListener('close', (event) => {
    console.log('Connection closed');
    // Attempt to reconnect
    setTimeout(openConnection, 1000); // Retry after 1 second
  });
  console.log("Connected to the WebSocket server");
}

openConnection();

function handleIncomingData(data) {
  if (!data.message) {
  nodeEventHandler(data.node);
  nodeNumber = nodeDict[data.node];
  temperature = data.Temp;
  humidity = data.Humi;
  CO2 = data.eCO2;
  TVOC = data.TVOC;

  updateNodeData(nodeNumber, temperature, humidity, CO2, TVOC);
  }
}

function nodeEventHandler(node) {
  if (!nodeArray.includes(node)) {
    nodeArray.push(node);
    nodeDict[node] = nodeArray.length;

    makeLiveGraph(nodeArray.length);    
  }
}

function makeLiveGraph(node) {
  createNodeData(node);
  liveGraphs.push(new liveGraph(node));

  console.log("Node " + node + " added to the liveGraphs array");

  liveGraphs[node - 1].makeGraph();
}

//function for making the html elements for the following html code
function nodeData(data, node) {
  let nodeData = document.createElement("div");
  nodeData.innerHTML = data;
  // nodeData.setAttribute("id", "node" + node);
  document.body.appendChild(nodeData);
  // console.log("Hello World");
}

function createNodeData(node) {
  // Create main div
  let nodeData = document.createElement("div");
  nodeData.className = "nodeData";

  // Create flex-NodeData div
  let flexNodeData = document.createElement("div");
  flexNodeData.className = "flex-NodeData";

  // Create p element
  let pNode = document.createElement("p");
  pNode.textContent = "Node " + node;

  // Append p to flex-NodeData
  flexNodeData.appendChild(pNode);

  // Create flex-LiveData div
  let flexLiveData = document.createElement("div");
  flexLiveData.className = "flex-LiveData";

  // Create data divs (Temperature, Humidity, Light Intensity)
  let dataTypes = ["Temperatuur", "Luchtvochtigheid", "CO2", "TVOC"];
  let ids = ["temperature", "humidity", "CO2", "TVOC"];
  let statusIds = ["tempStatus", "humidStatus", "CO2Status", "TVOCStatus"];

  for (let i = 0; i < dataTypes.length; i++) {
      let dataDiv = document.createElement("div");

      let dataTypeDiv = document.createElement("div");
      dataTypeDiv.textContent = dataTypes[i] + ": ";

      let pElement = document.createElement("p");
      pElement.id = ids[i] + node;
      pElement.textContent = "Not connected";

      dataTypeDiv.appendChild(pElement);
      dataDiv.appendChild(dataTypeDiv);

      let statusElement = document.createElement("div");
      statusElement.className = "statusElement";

      let statusText = document.createElement("p");
      statusText.className = "statusText";
      statusText.id = statusIds[i];
      statusText.textContent = "Not connected";

      statusElement.appendChild(statusText);
      dataDiv.appendChild(statusElement);

      flexLiveData.appendChild(dataDiv);
  }

  // Append flex-LiveData to flex-NodeData
  flexNodeData.appendChild(flexLiveData);

  // Create flex-graph div
  let flexGraph = document.createElement("div");
  flexGraph.className = "flex-graph";

  let graphDiv = document.createElement("div");

  let graphP = document.createElement("p");
  graphP.textContent = "Live graph:";

  let liveGraph = document.createElement("div");
  liveGraph.id = "liveGraph" + node;

  graphDiv.appendChild(graphP);
  graphDiv.appendChild(liveGraph);
  flexGraph.appendChild(graphDiv);

  // Append flex-graph to flex-NodeData
  flexNodeData.appendChild(flexGraph);

  // Append flex-NodeData to main div
  nodeData.appendChild(flexNodeData);

  // Check if nodeDataLocation element exists
  let nodeDataLocation = document.getElementById("nodeDataLocation");
  if (nodeDataLocation) {
    // Append main div to nodeDataLocation
    nodeDataLocation.appendChild(nodeData);
  } else {
    console.error("Element with ID 'nodeDataLocation' does not exist.");
  }
}

function updateNodeData(node, temperature, humidity, eCO2, TVOC) {
  // Update the temperature, humidity and light intensity values
  document.getElementById("temperature" + node).textContent = temperature;
  document.getElementById("humidity" + node).textContent = humidity;
  document.getElementById("CO2" + node).textContent = eCO2;
  document.getElementById("TVOC" + node).textContent = TVOC;

  // Update the status text
  document.getElementById("tempStatus").textContent = "Connected";
  document.getElementById("humidStatus").textContent = "Connected";
  document.getElementById("CO2Status").textContent = "Connected";
  document.getElementById("TVOCStatus").textContent = "Connected";

  // Update the graph
  liveGraphs[node - 1].updateData(temperature, humidity, eCO2, TVOC);
  liveGraphs[node - 1].updateGraph();
}