#include "packet.h"
#include "FreeRTOS.h"
#include "task.h"
#include "nrf_log.h"
#include "radio.h"
#include "radio_config.h"


#define PERIPH_NUM   2// 1//1..2 //used to differ p0 and p1
#define	PAYLOAD_SIZE	64  //bytes


upload_fifo_t upload_fifo;
static radio_data_t data_send;

uint8_t data_packet[] = {1,  0,  3,  4,  5,  6,  7,  8,
                         9, 10, 11, 12, 13, 14, 15, 16,
                         17, 18, 19, 20, 21, 22, 23, 24,
                         25, 26, 27, 28, 29, 30, 31, 32,
                         33, 34, 35, 36, 37, 38, 39, 40,
                         41, 42, 43, 44, 45, 46, 47, 48,
                         49, 50, 51, 52, 53, 54, 55, 56,
                         57, 58, 59, 60, 61, 62, 63, 64 };


upload_cell_t *get_cell_in_specify_state(UPLOAD_CELL_STATE_t state)
{
    uint8_t index;
    upload_cell_t *cell = &upload_fifo.cell_array[0];

    for(index = 0; index < UPLOAD_FIFO_SIZE; index++)
    {
        if(cell->state == state)
        {
            return cell;
        }else
        {
            cell = &upload_fifo.cell_array[index];
        }
    }

    NRF_LOG_ERROR("NO cell in state=%d", state);

    return NULL;
}


void radio_evt_cb(uint8_t radio_event)
{
    if(radio_event == RADIO_PERIPH_DATA_SENT)
    {
        // Set LEDs identical to the ones on the PTX.
        /*nrf_gpio_pin_write(LED_1, !(data_send.data[1]%8>0 && data_send.data[1]%8<=4));
        nrf_gpio_pin_write(LED_2, !(data_send.data[1]%8>1 && data_send.data[1]%8<=5));
        nrf_gpio_pin_write(LED_3, !(data_send.data[1]%8>2 && data_send.data[1]%8<=6));
        nrf_gpio_pin_write(LED_4, !(data_send.data[1]%8>3));

        data_send.data[1]++;*/
        //radio_put_packet(&data_send);
    }
}


void data_init(void)
{
    data_send.length = PAYLOAD_SIZE;
    data_send.periph_num = PERIPH_NUM;
    memcpy(data_send.data, data_packet, PAYLOAD_SIZE);
}


void period_upload_tx_entry(void *args)
{
    upload_cell_t *cell = NULL;

    data_init();
    radio_setup(false, RADIO_TX_POWER_0DBM, radio_evt_cb, PERIPH_NUM);

    while(1)
    {
        cell = get_cell_in_specify_state(CELL_READY);
        if(cell == NULL)
        {
            vTaskDelay(1);
            continue;
        }
        //radio_put_packet(radio_data_t * tx_data);
        //nrf_esb_write_payload(nrf_esb_payload_t const * p_payload);
        vTaskDelay(2);
    }
}


void period_upload_prepare_entry(void *args)
{
    while(1)
    {
    
    }
}
