var gateway = `ws://${window.location.hostname}/ws`;
var websocket;

var statusMapping;
var staticMapping;
var overlay;

document.addEventListener("DOMContentLoaded", function () {
  // Ihr JavaScript-Code hier, einschließlich der onLoad-Funktion
  overlay = document.getElementById("overlay");
  onLoad();
});

function initWebSocket() {
  console.log("Trying to open a WebSocket connection...");
  websocket = new WebSocket(gateway);
  websocket.onopen = onOpen;
  websocket.onclose = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function initButtons() {
  var elements = document.getElementsByClassName("btn-wsevent");

  if (elements.length > 0) {
    for (var i = 0; i < elements.length; i++) {
      let element = elements[i];
      element.addEventListener("click", sendButton);
    }
  }
}

function initSettingInputs() {
  var elements = document.getElementsByClassName("set-wsevent");

  if (elements.length > 0) {
    for (var i = 0; i < elements.length; i++) {
      let element = elements[i];
      element.addEventListener("change", function () {
        websocket_sendevent("set-" + element.id, element.value);
      });
    }
  }
}

function onOpen(event) {
  console.log("Connection opened");
}

function onClose(event) {
  console.log("Connection closed");
  setTimeout(initWebSocket, 1000);
  overlay.style.display = "flex";
}

function sendButton(event) {
  var targetElement = event.target;

  if (
    targetElement.classList.contains("confirm") &&
    window.confirm("Sicher?") == false
  )
    return;

  websocket_sendevent("btn-" + targetElement.id, targetElement.value);
}

function onMessage(event) {
  var data = event.data;
  console.log("ws_msg:" + event.data + "\n");

  if (data.startsWith("NOTIFY:")) {
    var notify_data = data.slice(7).split(";")[1];
    var notify_type = data.slice(7).split(";")[0];
    showNotification(notify_data, notify_type);
  } else if (data.startsWith("DEBUG:")) {
    var addtext = data.slice(6);
    var livedebug_out = document.getElementById("livedebug-out");
    livedebug_out.value += addtext;
    livedebug_out.scrollTop = livedebug_out.scrollHeight;
    do_resize(livedebug_out);
  } else if (data.startsWith("DTC:")) {
    const dtcs = data.slice(4);
    const dtcArray = dtcs.trim() !== "" ? dtcs.split(";").filter(Boolean) : [];

    processDTCNotifications(dtcArray);
    fillDTCTable(dtcArray);

  } else if (data.startsWith("MAPPING_STATUS:")) {
    const data_sliced = data.slice(15);
    statusMapping = createMapping(data_sliced);
  } else if (data.startsWith("MAPPING_STATIC:")) {
    const data_sliced = data.slice(15);
    staticMapping = createMapping(data_sliced);
  } else if (data.startsWith("STATUS:")) {
    const data_sliced = data.slice(7);
    const result = processDataString(data_sliced, statusMapping);
    console.log("STATUS:");
    console.log(JSON.stringify(result, null, 2));
    fillValuesToHTML(result);
  } else if (data.startsWith("STATIC:")) {
    const data_sliced = data.slice(7);
    const result = processDataString(data_sliced, staticMapping);
    console.log("STATIC:");
    console.log(JSON.stringify(result, null, 2));
    fillValuesToHTML(result);
    overlay.style.display = "none";
  }
}

function createMapping(mappingString) {
  const mappingArray = mappingString.split(";");
  const mapping = [];

  mappingArray.forEach((variable) => {
    if (variable !== null) mapping.push(variable.trim());
  });
  return mapping;
}

function processDataString(dataString, mapping) {
  const valuesArray = dataString.split(";");
  const dataObject = {};

  valuesArray.forEach((value, index) => {
    const variable = mapping[index];
    if (variable) {
      dataObject[variable] = value.trim();
    }
  });

  return dataObject;
}

function onLoad(event) {
  initWebSocket();
  initButtons();
  initSettingInputs();
  overlay.style.display = "flex";
}

function websocket_sendevent(element_id, element_value) {
  websocket.send(element_id + ":" + element_value);
}

function do_resize(textbox) {
  var maxrows = 15;
  var minrows = 3;
  var txt = textbox.value;
  var cols = textbox.cols;

  var arraytxt = txt.split("\n");
  var rows = arraytxt.length;

  for (i = 0; i < arraytxt.length; i++)
    rows += parseInt(arraytxt[i].length / cols);

  if (rows > maxrows) textbox.rows = maxrows;
  else if (rows < minrows) textbox.rows = minrows;
  else textbox.rows = rows;
}

function fillValuesToHTML(dataset) {
  for (var key in dataset) {
    var key_prefixed = "data-" + key;
    var elements = document.getElementsByClassName(key_prefixed);

    if (elements.length > 0) {
      for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        if (element.type === "checkbox") {
          // Wenn das Element ein Kontrollkästchen ist
          element.checked = dataset[key] == 1 ? true : false;
        } else if (element.tagName === "SELECT") {
          // Wenn das Element ein Dropdown ist
          setDropdownValue(element, dataset[key]);
        } else if (element.classList.contains("progress-bar")) {
          // Wenn das Element eine Fortschrittsleiste ist
          updateProgressBar(element, dataset[key]);
        } else if (element.classList.contains("hideable")) {
          // Wenn das Element ein Settingsabschnitt-div ist
          if (dataset[key] == 0) element.style.display = "none";
          else element.style.display = "";
        } else {
          // Standardmäßig für Textfelder und andere Elemente
          element.value = dataset[key];
        }
      }
    }
  }
}

// Funktion zum Setzen des ausgewählten Werts für Dropdowns
function setDropdownValue(selectElement, value) {
  for (var i = 0; i < selectElement.options.length; i++) {
    if (selectElement.options[i].value === value) {
      selectElement.selectedIndex = i;
      break;
    }
  }
}

// Funktion zum Aktualisieren der Fortschrittsleiste
function updateProgressBar(progressBar, value) {
  // Wert in das aria-valuenow-Attribut einfügen
  progressBar.setAttribute("aria-valuenow", value);

  // Breite des Fortschrittsbalkens und inneren Text aktualisieren
  progressBar.style.width = value + "%";
  progressBar.textContent = value + "%";
}

function showNotification(message, type) {
  // Erstellen Sie ein Bootstrap-Alert-Element
  var alertElement = $(
    '<div class="alert alert-' +
    type +
    ' alert-dismissible fade show notification" role="alert">' +
    "<strong>" +
    message +
    "</strong>" +
    '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
    '<span aria-hidden="true">&times;</span>' +
    "</button>" +
    "</div>"
  );

  // Fügen Sie das Alert-Element dem Container hinzu
  $("#notification-container").append(alertElement);

  // Nach 5 Sekunden das Alert-Element ausblenden
  setTimeout(function () {
    alertElement.alert("close");
  }, 5000);
}
