#include "config.hpp"
#include "lorahandler.hpp"
#include "logger.h"
#include "pins.hpp"

extern logging::Logger logger;
extern Config config;

void LoraHandler::setup()
{

    logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "LoRa", "Set SPI pins!");
    SPI.begin(RADIO_SCK, RADIO_MISO, RADIO_MOSI, RADIO_CS);
    LoRa.setPins(RADIO_CS, RADIO_RST, RADIO_IRQ);

    long freq = config.loraConfig.frequency;
    if (!LoRa.begin(freq))
    {
        logger.log(logging::LoggerLevel::LOGGER_LEVEL_ERROR, "LoRa", "Starting LoRa failed!");
        // show_display("ERROR", "Starting LoRa failed!");
        while (true)
        {
            delay(1000);
        }
    }
    LoRa.setSpreadingFactor(config.loraConfig.spreadingFactor);
    LoRa.setSignalBandwidth(config.loraConfig.signalBandwidth);
    LoRa.setCodingRate4(config.loraConfig.codingRate4);
    LoRa.enableCrc();
    LoRa.setTxPower(config.loraConfig.power);
    logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "LoRa", "LoRa init done!");
    String currentLoRainfo = "LoRa Freq: " + String(config.loraConfig.frequency) + " / SF:" + String(config.loraConfig.spreadingFactor) + " / CR: " + String(config.loraConfig.codingRate4);
    logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "LoRa", currentLoRainfo.c_str());
}

ReceivedLoRaPacket LoraHandler::receivePacket()
{
    ReceivedLoRaPacket receivedLoraPacket;
    String packet = "";
    int packetSize = LoRa.parsePacket();
    if (packetSize)
    {
        while (LoRa.available())
        {
            int inChar = LoRa.read();
            packet += (char)inChar;
        }
        receivedLoraPacket.text = packet;
        receivedLoraPacket.rssi = LoRa.packetRssi();
        receivedLoraPacket.snr = LoRa.packetSnr();
        receivedLoraPacket.freqError = LoRa.packetFrequencyError();
        logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "LoRa Rx", "---> %s", packet.c_str());
    }
    return receivedLoraPacket;
}