#include "share_buffer.h"
#define RING_BUFFER_SIZE 512

typedef struct {
    int buffer[RING_BUFFER_SIZE];
    int head;
    int tail;
    int count;
} RingBuffer;

// 两路环形缓冲区
RingBuffer ring_buffers[4];

// 初始化环形缓冲区
void init_ring_buffer(int channel) {
    if (channel < 0 || channel > 1) return;
    
    ring_buffers[channel].head = 0;
    ring_buffers[channel].tail = 0;
    ring_buffers[channel].count = 0;
}

// 初始化所有环形缓冲区
void init_all_ring_buffers() {
    init_ring_buffer(0);
    init_ring_buffer(1);
}

// 判断环形缓冲区是否为空
int is_ring_buffer_empty(int channel) {
    if (channel < 0 || channel > 3) return 1;
    
    return (ring_buffers[channel].count == 0);
}

// 判断环形缓冲区是否已满
int is_ring_buffer_full(int channel) {
    if (channel < 0 || channel > 3) return 0;
    
    return (ring_buffers[channel].count == RING_BUFFER_SIZE);
}

// 获取环形缓冲区中的数据数量
int get_ring_buffer_count(int channel) {
    if (channel < 0 || channel > 3) return 0;
    
    return ring_buffers[channel].count;
}

// 向环形缓冲区写入数据
int write_to_ring_buffer(int channel, int value) {
    if (channel < 0 || channel > 3) return -1;
    
    if (is_ring_buffer_full(channel)) {
        return -1; // 缓冲区已满
    }
    
    ring_buffers[channel].buffer[ring_buffers[channel].head] = value;
    ring_buffers[channel].head = (ring_buffers[channel].head + 1) % RING_BUFFER_SIZE;
    ring_buffers[channel].count++;
    
    return 0; // 写入成功
}

// 从环形缓冲区读取数据
int read_from_ring_buffer(int channel) {
    int value = 0;
    if (channel == 0 || channel == 1 || channel == 2 || channel == 3) {
        if (is_ring_buffer_empty(channel)) {
            return 0;
        }

        value = ring_buffers[channel].buffer[ring_buffers[channel].tail];
        ring_buffers[channel].tail = (ring_buffers[channel].tail + 1) % RING_BUFFER_SIZE;
        ring_buffers[channel].count--;
    }
    return value;
}

// 清空环形缓冲区
void clear_ring_buffer(int channel) {
    if (channel < 0 || channel > 3) return;
    
    ring_buffers[channel].head = 0;
    ring_buffers[channel].tail = 0;
    ring_buffers[channel].count = 0;
}

// 清空所有环形缓冲区
void clear_all_ring_buffers() {
    clear_ring_buffer(0);
    clear_ring_buffer(1);
    clear_ring_buffer(2);
    clear_ring_buffer(3);
}
