#pragma once

#include <Arduino.h>

#include "i2s_settings.h"

// ===== AudioBuffer Class =====
// This class manages two buffers (double buffering) for stereo audio.
// It provides a method to update the inactive buffer with new mono PCM data
// (converted to stereo) and a semaphore to signal when new data is available.
class AudioBuffer {
public:
  AudioBuffer();
  // Update the inactive buffer with fresh mono PCM data (in uint8_t form)
  void updateBuffer(const uint8_t *monoData, size_t byteCount);
  // Wait for new data (with timeout in milliseconds); returns true if data is
  // ready.
  bool waitForNewData(uint32_t timeout_ms);
  // Returns a pointer to the active (ready to play) buffer.
  const uint8_t *getActiveBuffer();
  // Swap the active and inactive buffers.
  void swapBuffers();
  // Fill the inactive buffer with silence (all zeros).
  void fillInactiveBufferWithSilence();

private:
  uint8_t buffer0[STEREO_BUFFER_SIZE];
  uint8_t buffer1[STEREO_BUFFER_SIZE];
  // Pointers to the active (to be played) and inactive (to be updated) buffers.
  volatile uint8_t *activeBuffer;
  volatile uint8_t *inactiveBuffer;
  // Semaphore used to signal that new data is available.
  SemaphoreHandle_t semaphore;
};