#include "Logger.h"

constexpr size_t LOG_SIZE = 1024 * 1024 * 2;

static Logger *theLogger = nullptr;

Logger *Logger::getInstance()
{
  return theLogger;
}

void Logger::init()
{
  theLogger = new Logger();
  Serial.begin(115200);
  while (!Serial)
  {
  }
}

Logger::Logger()
{
  data_ = (char *)heap_caps_malloc(LOG_SIZE, MALLOC_CAP_SPIRAM);
  totalSize_ = LOG_SIZE;
  currentSize_ = 0;

  // write header placeholder
  const auto millisPlaceholder = 0;
  memcpy(&data_[currentSize_], &millisPlaceholder, sizeof(millisPlaceholder));
  currentSize_ += sizeof(millisPlaceholder);

  NtpTimeT ntpPlaceholder = 0;
  memcpy(&data_[currentSize_], &ntpPlaceholder, sizeof(ntpPlaceholder));
  currentSize_ += sizeof(ntpPlaceholder);
}

void Logger::setNtpTime(NtpTimeT ntpTime)
{
  auto data = getInstance()->data_;

  const auto millisTime = millis();
  memcpy(&data[0], &millisTime, sizeof(millisTime));
  memcpy(&data[sizeof(millisTime)], &ntpTime, sizeof(ntpTime));
}


Logger::~Logger()
{
  free(data_);
}