#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "freertos/xtensa_api.h"
#include "freertos/FreeRTOSConfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/i2s.h"
#include "freertos/ringbuf.h"

static xTaskHandle h2201_i2s_task_handle = NULL;
static RingbufHandle_t h2201_i2s_ringbuffer_handle = NULL;

static void h2201_i2s_task(void *arg)
{
    uint8_t *data = NULL;
    size_t item_size = 0;
    size_t bytes_written = 0;

    for (;;)
    {
        data = (uint8_t *)xRingbufferReceive(h2201_i2s_ringbuffer_handle, &item_size, (portTickType)portMAX_DELAY);
        if (item_size != 0)
        {
            i2s_write(0, data, item_size, &bytes_written, portMAX_DELAY);
            vRingbufferReturnItem(h2201_i2s_ringbuffer_handle, (void *)data);
        }
    }
}

void h2201_i2s_task_start_up(void)
{
    h2201_i2s_ringbuffer_handle = xRingbufferCreate(8 * 1024, RINGBUF_TYPE_BYTEBUF);
    if (h2201_i2s_ringbuffer_handle == NULL)
    {
        return;
    }

    xTaskCreate(h2201_i2s_task, "BtI2ST", 1024, NULL, configMAX_PRIORITIES - 3, &h2201_i2s_task_handle);
    return;
}

void h2201_i2s_task_shut_down(void)
{
    if (h2201_i2s_task_handle)
    {
        vTaskDelete(h2201_i2s_task_handle);
        h2201_i2s_task_handle = NULL;
    }

    if (h2201_i2s_ringbuffer_handle)
    {
        vRingbufferDelete(h2201_i2s_ringbuffer_handle);
        h2201_i2s_ringbuffer_handle = NULL;
    }
}

size_t h2201_i2s_write_ringbuf(const uint8_t *data, size_t size)
{
    BaseType_t done = xRingbufferSend(h2201_i2s_ringbuffer_handle, (void *)data, size, (portTickType)portMAX_DELAY);
    if (done)
    {
        return size;
    }
    else
    {
        return 0;
    }
}