// /components/main/settingsPageComponents/handlers/handleGeneralSubmit.ts

const handleGeneralSubmit = (
  original: {
    name: string;
    ip: string;
    subnet: string;
    gateway: string;
  },
  current: {
    name: string;
    ip: string;
    subnet: string;
    gateway: string;
  }
) => {
  const changes: { [key: string]: string } = {};
  let networkChanges = false;
  let newIp: string | null = null;

  if (current.name !== original.name) {
    changes.SNNA = current.name;
    networkChanges = true;
  }
  if (current.ip !== original.ip) {
    changes.SEI01 = current.ip;
    newIp = current.ip;
    networkChanges = true;
  }
  if (current.subnet !== original.subnet) {
    changes.SEI02 = current.subnet;
    networkChanges = true;
  }
  if (current.gateway !== original.gateway) {
    changes.SEI03 = current.gateway;
    networkChanges = true;
  }

  if (Object.keys(changes).length === 0) {
    alert("Keine Änderungen vorgenommen.");
    return;
  }

  let url = `${window.location.origin}/CPL?${window.location.pathname}`;
  Object.entries(changes).forEach(([key, value]) => {
    url += `&${key}=${encodeURIComponent(value)}`;
  });

  console.log("URL für Allgemeine Einstellungen: ", url);
  console.log("Original:", original);
  console.log("Current:", current);
  console.log("Changes:", changes);

  fetch(url, { method: "GET" })
    .then(() => {
      alert("Daten erfolgreich gesendet!");
      if (networkChanges) {
        alert(
          "Ein Neustart ist erforderlich, um die Einstellungen zu übernehmen."
        );
        // Optional: handleReboot(newIp);
      }
    })
    .catch((err) => {
      console.error("Fehler:", err);
      alert("Fehler beim Senden der allgemeine Einstellungen.");
    });
};

export default handleGeneralSubmit;
