#include "AudioBuffer.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.

AudioBuffer::AudioBuffer() {
  memset(buffer0, 0, sizeof(buffer0));
  memset(buffer1, 0, sizeof(buffer1));
  activeBuffer = buffer0;
  inactiveBuffer = buffer1;
  semaphore = xSemaphoreCreateBinary();
  if (semaphore == NULL) {
    Serial.println("Failed to create semaphore");
  }
}

void AudioBuffer::updateBuffer(const uint8_t *monoData, size_t byteCount) {
  if (byteCount != BUFFER_SAMPLES * SAMPLE_SIZE) {
    Serial.println("Warning: Unexpected byte count.");
  }
  // Convert each 16-bit mono sample (2 bytes) into stereo (copy the sample to
  // both channels).
  for (size_t i = 0; i < BUFFER_SAMPLES; i++) {
    size_t monoOffset = i * 2;   // Two bytes per mono sample
    size_t stereoOffset = i * 4; // Four bytes per stereo sample
    inactiveBuffer[stereoOffset] = monoData[monoOffset];         // Left LSB
    inactiveBuffer[stereoOffset + 1] = monoData[monoOffset + 1]; // Left MSB
    inactiveBuffer[stereoOffset + 2] = monoData[monoOffset];     // Right LSB
    inactiveBuffer[stereoOffset + 3] = monoData[monoOffset + 1]; // Right MSB
  }
  // Signal that new data is available.
  xSemaphoreGive(semaphore);
}

bool AudioBuffer::waitForNewData(uint32_t timeout_ms) {
  return (xSemaphoreTake(semaphore, pdMS_TO_TICKS(timeout_ms)) == pdTRUE);
}

const uint8_t *AudioBuffer::getActiveBuffer() {
  return (const uint8_t *)activeBuffer;
}

void AudioBuffer::swapBuffers() {
  volatile uint8_t *temp = activeBuffer;
  activeBuffer = inactiveBuffer;
  inactiveBuffer = temp;
}

void AudioBuffer::fillInactiveBufferWithSilence() {
  // memset((void *)inactiveBuffer, 0, STEREO_BUFFER_SIZE);

  // Get the last sample (4 bytes) from the active buffer
  uint8_t lastSample[4];
  memcpy(lastSample, (const uint8_t *)&activeBuffer[STEREO_BUFFER_SIZE - 4], 4);

  // Fill the inactive buffer with the last sample
  for (size_t i = 0; i < STEREO_BUFFER_SIZE; i += 4) {
    memcpy((uint8_t *)&inactiveBuffer[i], lastSample, 4);
  }
}