// utils/loadWindowVariables.js
export async function loadWindowVariables() {
  return new Promise((resolve, reject) => {
    const requiredVars = [
      "win_last20Messages",
      "win_deviceName",
      "win_mac1",
      "win_ip",
      "win_subnet",
      "win_gateway",
      "win_cplInternalTimestamp",
      "win_ntp1",
      "win_ntp2",
      "win_ntp3",
      "win_systemZeit",
      "win_ntpTimezone",
      "win_ntpActive",
      "win_de",
      "win_counter",
      "win_flutter",
      "win_kueOnline",
      "win_kueID",
      "win_kuePSTmMinus96V",
      "win_kueAlarm1",
      "win_kueAlarm2",
      "win_kueIso",
      "win_kueResidence",
      "win_kueCableBreak",
      "win_kueGroundFault",
      "win_kueLimit1",
      "win_kueLimit2Low",
      "win_kueDelay1",
      "win_kueLoopInterval",
      "win_kueVersion",
      "win_tdrAtten",
      "win_tdrPulse",
      "win_tdrSpeed",
      "win_tdrAmp",
      "win_tdrTrigger",
      "win_tdrLocation",
      "win_tdrActive",
      "win_kueOverflow",
      "win_tdrLast",
      "win_appVersion",
    ];

    const loadScript = (src) => {
      return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        const environment = process.env.NEXT_PUBLIC_NODE_ENV || "production";
        script.src =
          environment === "production"
            ? `/CPL?/CPL/SERVICE/${src}`
            : `/CPLmockData/SERVICE/${src}`;
        script.async = true;
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    };

    const scripts = ["de.js", "kueData.js", "Start.js", "System.js"];

    scripts
      .reduce(
        (promise, script) => promise.then(() => loadScript(script)),
        Promise.resolve()
      )
      .then(() => {
        const variablesObj = requiredVars.reduce((acc, variable) => {
          if (window[variable] !== undefined) {
            // Wenn es sich um kueID handelt, ersetze %20 durch Leerzeichen
            if (variable === "win_kueID" && Array.isArray(window[variable])) {
              acc[variable.replace("win_", "")] = window[variable].map((id) =>
                id.replace(/%20/g, " ")
              );
            } else {
              acc[variable.replace("win_", "")] = window[variable];
            }
          }
          return acc;
        }, {});
        resolve(variablesObj);
      })
      .catch((error) => {
        console.error("Fehler beim Laden eines Skripts:", error);
        reject(error);
      });
  });
}
