#define NRFX_I2S_ENABLED 1

#include <zephyr.h>
#include "buttonLed.h"
#include <nrfx_i2s.h>


#define BUFFER_SIZE	200
#define PING_BUFFER_DATA_READY	0
#define PONG_BUFFER_DATA_READY	1

uint32_t rxBufferPing[BUFFER_SIZE] = {0};
uint32_t rxBufferPong[BUFFER_SIZE] = {0};
uint32_t txBufferDummy[BUFFER_SIZE] = {'d', 'e', 'a', 'd', 'b', 'e', 'e', 'f'};

nrfx_i2s_buffers_t rx_buffer_ping = {
	.p_rx_buffer = rxBufferPing,
	.p_tx_buffer = txBufferDummy
};

nrfx_i2s_buffers_t rx_buffer_pong = {
	.p_rx_buffer = rxBufferPong,
	.p_tx_buffer = txBufferDummy
};

volatile int whichBuffer = PING_BUFFER_DATA_READY;

volatile int i = 0;

static void i2s_data_handler(nrfx_i2s_buffers_t const* p_released, uint32_t status){
	
	// data corruption if p_released is null
	i++;

	if(i % 10000 == 0){
		led_toggle(LED0);
		i = 0;
	}
	nrfx_i2s_buffers_t* nextBuffer;
	if(p_released == &rx_buffer_ping){
		nextBuffer = &rx_buffer_pong;
		whichBuffer = PING_BUFFER_DATA_READY;
	}else{
		nextBuffer = &rx_buffer_ping;
		whichBuffer = PONG_BUFFER_DATA_READY;
	}



	nrfx_i2s_next_buffers_set(nextBuffer);
}

int main()
{
	// sanity check
	//buttonLed_init();

	led_init();

	IRQ_CONNECT(DT_IRQN(DT_NODELABEL(i2s0)),
		    DT_IRQ(DT_NODELABEL(i2s0), priority),
		    nrfx_isr, nrfx_i2s_irq_handler, 0);

	// i2s format is unaligned, but alignment param is mandatory
	// NOTE: change priority

	// LRCK = MCK/Ratio
	// SCK = LRCK * 2 * SWIDTH
	// Ratio >= 2 * SWIDTH
	// SWIDTH = 24
	// Ratio = 96
	// MCK = 761904.8
	// LRCK = 7936.5 (audio sampling rate)
	// SCK = 380952.4
	nrfx_i2s_config_t p_config = {
		.sck_pin = 10,
		.lrck_pin = 33,
		.mck_pin = 36,
		.sdout_pin = 37,
		.sdin_pin = 38,             
		.irq_priority = DT_IRQ(DT_NODELABEL(i2s0), priority),
		.mode = 0,
		.format = 0,
		.alignment = 0,
		.sample_width = 2,
		.channels = 2,
		.mck_setup = 16,
		.ratio = 3
	};

	volatile nrfx_err_t err0 = nrfx_i2s_init(&p_config, i2s_data_handler);
	irq_enable(DT_IRQN(DT_NODELABEL(i2s0)));

	while(1){

		int i_temp = i;
		volatile nrfx_err_t err1 = nrfx_i2s_start(&rx_buffer_ping, BUFFER_SIZE, 0);
		while(i_temp >= i){

		}
		nrfx_i2s_stop();
		
	}



	return 0;
}
