#pragma once

#include <Bytes.h>
#include <Interface.h>

#include <Arduino.h>
#include <RadioLib.h>
#include <SPI.h>

class TBeamSupremeLoRaInterface : public RNS::InterfaceImpl {
public:
  explicit TBeamSupremeLoRaInterface(const char* name = "TBeamSupremeLoRa");
  ~TBeamSupremeLoRaInterface() override;

  bool start() override;
  void stop() override;
  void loop() override;

  float last_rssi() const { return _last_rssi; }
  float last_snr() const { return _last_snr; }

private:
  void send_outgoing(const RNS::Bytes& data) override;
  void on_incoming(const RNS::Bytes& data);

  static constexpr uint8_t HEADER_SPLIT = 0x08;
  static constexpr uint8_t HEADER_SEQ_MASK = 0x07;
  static constexpr uint8_t SEQ_UNSET = 0xFF;
  static constexpr int LORA_MAX_PAYLOAD = 254;

  static bool is_split_packet(uint8_t header) { return (header & HEADER_SPLIT) != 0; }
  static uint8_t packet_sequence(uint8_t header) { return header & HEADER_SEQ_MASK; }

  RNS::Bytes _rx_buffer;
  uint8_t _rx_seq = SEQ_UNSET;
  uint8_t _tx_seq_ctr = 0;
  float _last_rssi = 0.0f;
  float _last_snr = 0.0f;

  Module* _module = nullptr;
  SX1262* _radio = nullptr;
};
