const puppeteer = require("puppeteer");
const path = require("path");

const JASONBOXINFO_URL = "http://192.168.178.1/jason_boxinfo.xml";
const BROWSER_PATH = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";

function jasonSerialToMac(serial) {
  return serial.match(/.{1,2}/g).slice(0, 5).join(":");
}

async function fetchSerial() {
  const browser = await puppeteer.launch({
    headless: "new",
    executablePath: BROWSER_PATH,
    args: ["--no-sandbox", "--disable-setuid-sandbox"]
  });

  const page = await browser.newPage();
  await page.goto(JASONBOXINFO_URL, { waitUntil: "domcontentloaded" });
  const body = await page.evaluate(() => document.body.innerText);
  await browser.close();

  const serialMatch = body.match(/<j:Serial>(.+?)<\/j:Serial>/);
  if (!serialMatch || !serialMatch[1]) {
    throw new Error("❌ Keine gültige Serial gefunden!");
  }
  const typMatch = body.match(/<j:Name>(.+?)<\/j:Name>/)

  if (!typMatch || !typMatch[1]) {
    throw new Error("❌ Kein Geräte Typ gefunden!")
  }

  return {
    serial: serialMatch[1].trim(),
    typ: typMatch[1].trim(),
  }
  

}

(async function main() {
  try {
    console.log("\n--- Mac-Test gestartet ---");
    const { serial, typ } = await fetchSerial();
    const mac = jasonSerialToMac(serial);

    console.log("\n📋 Geräte Infos:\n");
    console.log("Typ:    ", typ);
    console.log("Serial: ", serial);
    console.log("MAC:    ", mac);
    console.log("\n--- Mac-Test beendet ---\n");
  } catch (err) {
    console.error("❌ Fehler beim MAC-Test:", err.message || err);
  }
})();
