#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 TaskHandle_t h2201_i2s_task_handle = NULL;
static RingbufHandle_t h2201_i2s_ringbuffer_handle = NULL;
static const int i2s_num = 0; // i2s port number

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, (TickType_t)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;
    }
}

void h2201_i2s_write_ringbuf(const uint8_t *data, uint32_t size)
{
    xRingbufferSend(h2201_i2s_ringbuffer_handle, (void *)data, size, (TickType_t)portMAX_DELAY);
}

void h2201_i2s_set_samplerate(int sample_rate)
{
    i2s_set_clk(i2s_num, sample_rate, 16, 2);
}

void h2201_i2s_init(void)
{
    i2s_config_t i2s_config = {
        .mode = I2S_MODE_MASTER | I2S_MODE_TX, // Only TX
        .sample_rate = 48000,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
        .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, // 2-channels
        //.channel_format = I2S_CHANNEL_FMT_MULTIPLE, // multi channel
        .communication_format = I2S_COMM_FORMAT_STAND_I2S,
        .dma_buf_count = 8,
        .dma_buf_len = 64,
        .intr_alloc_flags = 0, // Default interrupt priority
        .use_apll = true,
        .fixed_mclk = 12288000, //12.288 Mhz
        .tx_desc_auto_clear = true // Auto clear tx descriptor on underflow
        //.chan_mask = I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1
    };
    i2s_driver_install(i2s_num, &i2s_config, 0, NULL);

    i2s_pin_config_t pin_config = {
        .mck_io_num = 0,
        .bck_io_num = 25,
        .ws_io_num = 26,
        .data_out_num = 33,
        .data_in_num = I2S_PIN_NO_CHANGE};
    i2s_set_pin(i2s_num, &pin_config);
}