#include "pipe.h"
//#include "ch57x_common.h"
#include "hidreport.h"
#include "api.h"

#if DEBUG == Debug_USB
Pipe_t debug_pipe = {0,0};
#endif

Pipe_t sys_pipe;
Pipe_t coor_pipe;
Pipe_t uart_cmd_pipe;
extern UINT8 print_log;
void pipe_init(Pipe_t *pipe)
{
	pipe->tail = pipe->header = 0;
}

UINT8 pipe_read(Pipe_t *pipe, UINT8 * value, UINT8 len)
{
    GLOBAL_INT_DISABLE();
	UINT8 cnt = 0;
	do
	{
		if(pipe->tail==pipe->header)
		{
			break;
		}

		value[cnt++] = pipe->buf[pipe->tail];

		pipe->tail = (pipe->tail+1)&OFFSET_MASK;//%BUF_MAX;

	}while(--len);

	GLOBAL_INT_RESTORE();

	return cnt;
}

void pipe_write_c(Pipe_t *pipe, UINT8 value)
{
    GLOBAL_INT_DISABLE();
	pipe->buf[pipe->header] = value;

	pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;

	if(pipe->tail==pipe->header)
	{
		pipe->tail = (pipe->tail+1)&OFFSET_MASK;//%BUF_MAX;
	}
	GLOBAL_INT_RESTORE();
}

void pipe_write(Pipe_t *pipe, UINT8* value, UINT8 len)
{
  UINT8 cnt = 0;

  GLOBAL_INT_DISABLE();

  UINT16 res = pipe->tail <= pipe->header ? pipe->tail + BUF_MAX - pipe->header : pipe->tail -  pipe->header;
  if(res < len)
  {
      GLOBAL_INT_RESTORE();
    return;
  }

  while(cnt < len)
  {
    pipe->buf[pipe->header] = value[cnt++];

    pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;
  }
  GLOBAL_INT_RESTORE();
}


void pipe_write_t(Pipe_t *pipe, UINT8* value, UINT8 len, COMMAND_TYPE cmd)
{
    GLOBAL_INT_DISABLE();
	UINT8 cnt = 0;

	UINT16 res = pipe->tail <= pipe->header ? pipe->tail + BUF_MAX - pipe->header : pipe->tail -  pipe->header;
	if(res < len+2)
	{
	    GLOBAL_INT_RESTORE();
		return;
	}

	pipe_write_c(pipe, len);

	pipe_write_c(pipe, cmd);

	while(cnt < len)
	{
		pipe->buf[pipe->header] = value[cnt++];

		pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;
	}
	GLOBAL_INT_RESTORE();
}



