‭// AES-128 nøgle i base64 (samme som afsender)‬
const aesKey = 'MTIzNDU2Nzg5MGFiY2RlZg==';
const CHECKSUM_SIZE = 4;

// Hjælpefunktioner

function base64ToBytes(b64) {
  const bin = atob(b64);
  const bytes = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) {
    bytes[i] = bin.charCodeAt(i);
  }
  return bytes;
}

function generateChecksum(msg) {
  let checksum = 0;
  for (let i = 0; i < msg.length; i++) {
    checksum ^= msg.charCodeAt(i);
  }
  let hexChecksum = checksum.toString(16);
  while (hexChecksum.length < CHECKSUM_SIZE) {
    hexChecksum = '0' + hexChecksum;
  }
  return hexChecksum.slice(-CHECKSUM_SIZE);
}

function verifyMessage(message) {
  if (message.length < CHECKSUM_SIZE + 1) {
    console.log('[LoRa] Ugyldig besked – for kort');
    return;
  }

  const receivedCheckSum = message.slice(0, CHECKSUM_SIZE);
  const _message = message.slice(CHECKSUM_SIZE);
  const expectedChecksum = generateChecksum(_message);

  if (receivedCheckSum !== expectedChecksum) {
    console.log('[LoRa] Ugyldig besked – forkert checksum');
    return;
  }

  return _message;
}

function decryptMessage(buffer, keyBase64) {
  if (typeof AES === 'undefined') {
    console.log("ERROR: AES ikke understøttet på enheden");
    return;
  }

  function toHex(buffer) {
    let s = '';
    for (let i = 0; i < buffer.length; i++) {
      s += (256 + buffer[i]).toString(16).substr(-2);
    }
    return s;
  }

  function hex2a(hex) {
    let str = '';
    for (let i = 0; i < hex.length; i += 2) {
      str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    }
    return str;
  }

  const key = base64ToBytes(keyBase64);
  const decrypted = AES.decrypt(buffer, key, { mode: 'ECB' });

  if (!decrypted || decrypted.byteLength === 0) {
    console.log('[LoRa] Dekryptering gav tomt resultat');
    return;
  }

  const hex = toHex(decrypted);
  const fullMessage = hex2a(hex).trim();
  return verifyMessage(fullMessage);
}

// Håndtering af LoRa-beskeder

Shelly.addEventHandler(function (event) {
  if (!event || event.name !== 'lora' || event.id !== 100 || !event.info || !event.info.data) {
    return;
  }

  const encryptedMsg = atob(event.info.data);
  const decryptedMessage = decryptMessage(encryptedMsg, aesKey);

  if (typeof decryptedMessage === "undefined") {
    return; // Ignorer ugyldig besked
  }

  console.log("Dekrypteret besked:", decryptedMessage);

  if (decryptedMessage === "ON") {
    console.log("Tænder relæ (modtog 'ON')");
    Shelly.call("Switch.set", { id: 0, on: true });
  } else if (decryptedMessage === "OFF") {
    console.log("Slukker relæ (modtog 'OFF')");
    Shelly.call("Switch.set", { id: 0, on: false });
  } else {
    console.log("Ukendt kommando:", decryptedMessage);
  }
});