#include <console.h>

#define RECV_BUF_SIZE 16
static char recv_buf[RECV_BUF_SIZE];
static unsigned char recv_buf_size= 0;
static unsigned recv_buf_in_ptr= 0;
static unsigned recv_buf_out_ptr= 0;

static command_t * _commands;

void console_init(command_t * commands) {
  _commands= commands;
}

static inline void _process_command() {
  if (recv_buf_size == 0) {
    print("\n\rcommand is empty\n\r");
    return;
  }
  char cmd[RECV_BUF_SIZE+1];
  unsigned char i;
  for (i= 0; i < recv_buf_size; i++) {
    cmd[i]= recv_buf[(recv_buf_out_ptr + i) % RECV_BUF_SIZE];
  }
  cmd[recv_buf_size]= 0;
  recv_buf_out_ptr= (recv_buf_out_ptr + recv_buf_size) % RECV_BUF_SIZE;
  recv_buf_size= 0;

  command_t * cmd_ptr= _commands;
  while (cmd_ptr->name != 0) {
    if (!strncmp(cmd_ptr->name, cmd, strlen(cmd_ptr->name))) {
      i= strlen(cmd_ptr->name);
      while ((cmd[i] == ' ') || (cmd[i] == '\t'))
	i++;
      cmd_ptr->fct(&cmd[i]);
      return;
    }
    cmd_ptr++;
  }
  print("console: unknown command \"");
  print(cmd);
  print("\"\n\r");
}

void console_recv(char c) {
  switch (c) {
  case '\n':
  case '\r':
    _process_command();
    break;
  default:
    if (recv_buf_size < RECV_BUF_SIZE) {
      recv_buf[recv_buf_in_ptr]= c;
      recv_buf_size++;
      recv_buf_in_ptr= (recv_buf_in_ptr + 1) % RECV_BUF_SIZE;
    } else
      print("\n\rrecv buffer full\n\r");
  }
}
