#include "UART_FIFO.h"

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
ring_buff_t ring_buff;

int ring_buff_init(char* buff, unsigned int size)
{
    ring_buff.buffer     = buff;
    ring_buff.size       = size;
		ring_buff.datalen = 0;
    ring_buff.readpoint  = 0;
    ring_buff.writepoint = 0;
    memset(ring_buff.buffer, 0, ring_buff.size);
    ring_buff.full = false;
		ring_buff.finishFlag = 0;
    return RINGBUFF_OK;
}

int ring_buff_flush(void)
{
    ring_buff.readpoint  = 0;
    ring_buff.writepoint = 0;
    memset(ring_buff.buffer, 0, ring_buff.size);
    ring_buff.full = false;
		memset(ring_buff.data,0,ring_buff.datalen);
    return RINGBUFF_OK;
}

int ring_buff_push_data(char* pData, int len)
{
    int i;

    if (len > ring_buff.size) {
        return RINGBUFF_TOO_SHORT;
    }

    for (i = 0; i < len; i++) {
        if (((ring_buff.writepoint + 1) % ring_buff.size) == ring_buff.readpoint) {
            ring_buff.full = true;
            return RINGBUFF_FULL;
        } else {
            if (ring_buff.writepoint < (ring_buff.size - 1)) {
                ring_buff.writepoint++;
            } else {
                ring_buff.writepoint = 0;
            }
            ring_buff.buffer[ring_buff.writepoint] = pData[i];
        }
    }

    return RINGBUFF_OK;
}

int ring_buff_pop_data(char* pData, int len)
{
    int i;

    if (len > ring_buff.size) {
        return RINGBUFF_TOO_SHORT;
    }

    for (i = 0; i < len; i++) {
        if (ring_buff.writepoint == ring_buff.readpoint) {
            break;
        } else {
            if (ring_buff.readpoint == (ring_buff.size - 1)) {
                ring_buff.readpoint = 0;
            } else {
                ring_buff.readpoint++;
            }
            pData[i] = ring_buff.buffer[ring_buff.readpoint];
        }
    }

    return i;
}

unsigned int ring_buff_get_size(void)
{
    if (ring_buff.writepoint == ring_buff.readpoint) {
        return 0;
    }
    if (ring_buff.writepoint > ring_buff.readpoint)
        return ring_buff.writepoint - ring_buff.readpoint;
    else
        return ring_buff.size - (ring_buff.readpoint - ring_buff.writepoint);
}
