‭// AES-128 nøgle i base64 (16 byte): base64 af "1234567890abcdef"‬
const aesKey = "MTIzNDU2Nzg5MGFiY2RlZg==";
const CHECKSUM_SIZE = 4;
let state = "unknown";

// --- AES Hjælpefunktioner ---

function padRight(msg, blockSize) {
  try {
    const paddingSize = (blockSize - msg.length % blockSize) % blockSize;
    let padding = "";
    for (let i = 0; i < paddingSize; i++) padding += " ";
    return msg + padding;
  } catch (err) {
    console.log("Fejl i padRight:", err.message);
    return msg;
  }
}

function base64ToBytes(b64) {
  try {
    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;
  } catch (err) {
    console.log("Fejl i base64ToBytes:", err.message);
    return new Uint8Array();
  }
}

function generateChecksum(msg) {
  try {
    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);
  } catch (err) {
    console.log("Fejl i generateChecksum:", err.message);
    return "0000";
  }
}

function encryptMessage(msg, keyB64) {
  try {
    if (typeof AES === 'undefined') {
      console.log("ERROR: AES ikke understøttet på enheden");
      return null;
    }
    const key = base64ToBytes(keyB64);
    const formattedMsg = padRight(msg.trim(), 16);
    return AES.encrypt(formattedMsg, key, { mode: 'ECB' });
  } catch (err) {
    console.log("Fejl i encryptMessage:", err.message);
    return null;
  }
}

// --- Krypteret beskedsender via LoRa ---

function sendMessage(message) {
  try {
    const checkSumMessage = generateChecksum(message) + message;
    const encryptedMessage = encryptMessage(checkSumMessage, aesKey);

    if (!encryptedMessage) {
      console.log("Kryptering fejlede – besked ikke sendt");
      return;
    }

    Shelly.call('Lora.SendBytes', {
      id: 100,
      data: btoa(encryptedMessage),
    }, function (_, err_code, err_msg) {
      if (err_code !== 0) {
        console.log('LoRa fejl:', err_code, err_msg);
      }
    });
  } catch (err) {
    console.log("Fejl i sendMessage:", err.message);
  }
}

// --- Sender krypteret ON/OFF besked ---

function send(state) {
  try {
    console.log('Relæstatus ændret – sender krypteret:', state);
    sendMessage(state);
  } catch (err) {
    console.log("Fejl i send:", err.message);
  }
}

// --- Relæovervågning ---

function checkRelayStatus() {
  try {
    Shelly.call("Switch.GetStatus", { id: 0 }, function (result, error) {
      if (error) {
        console.log("Fejl ved hentning af relæstatus:", error);
        return;
      }

      try {
        let newState = result.output ? "ON" : "OFF";
        if (newState !== state) {
          state = newState;
          console.log("Relæ tilstand ændret til:", state);
          send(state);
        }
      } catch (innerErr) {
        console.log("Fejl i behandling af relæstatus:", innerErr.message);
      }
    });
  } catch (err) {
    console.log("Fejl i checkRelayStatus:", err.message);
  }
}

// --- EventHandler for relæ ---

try {
  Shelly.addEventHandler(function (event) {
    try {
      if (event.name === "switch" && event.info.id === 0) {
        checkRelayStatus();
      }
    } catch (err) {
      console.log("Fejl i event handler:", err.message);
    }
  });
} catch (err) {
  console.log("Fejl ved opsætning af event handler:", err.message);
}