/*
 * comand_parser.c
 *
 * Created: 23-Feb-19 17:58:28
 * Author : Edwin
 */ 

#include <avr/io.h>
#include <stdint.h>
#include <string.h>
#include "entryf.h"
#include "hal_usart.h"
#include <avr/interrupt.h>

#define RX_BUFF_SIZE 100
#define ENTRY_LIST_SIZE 3
#define HUMAN_READABLE 0

char rx_buff[RX_BUFF_SIZE];
uint8_t rx_buff_index = 0;
uint8_t parse_FLG = 0;

typedef (*callback_t)();

typedef struct
{
	char *name;
	callback_t callback;
}entry_t;

uint8_t entryListIndex = 0;
entry_t entryList[ENTRY_LIST_SIZE]={{"led 1", turnOnLed},
									{"led 0", turnOffLed},
									{"led t", toggleLed}};


void rxCallback()
{
	char input = hal_USART_readDataReg();
	
	if(parse_FLG) return;
	
	// if(input == )
	
	// enter
	if(input == 13 ){
		rx_buff[rx_buff_index] = '\0';
		parse_FLG = 1;
		return;
	}
	
	// backspace
	if(input == 8 && rx_buff_index > 0){
		rx_buff_index--;
		hal_USART_putc(input);
		return;
	}
	
	if(rx_buff_index < (RX_BUFF_SIZE - 1) && !parse_FLG){
		rx_buff[rx_buff_index++] = input;
		hal_USART_putc(input);
	}
}

void parser()
{
	uint8_t i = 0;
	if(!parse_FLG) return;
	for(i = 0; i < ENTRY_LIST_SIZE && parse_FLG; i++) {
		//if(strncmp(entryList[i].name,rx_buff,rx_buff_index) == 0){
		if(strcmp(entryList[i].name,rx_buff) == 0){
			entryList[i].callback();
			rx_buff_index = 0;
			parse_FLG = 0;
			
			#if HUMAN_READABLE
			hal_USART_puts("\n\r>>");
			#endif
			
			return;
		}
	}
	#if HUMAN_READABLE
	hal_USART_puts("\n\rNo match found!");
	hal_USART_puts("\n\r>>");
	#else
	hal_USART_puts("nmf\n\r");
	#endif
	
	rx_buff_index = 0;
	parse_FLG = 0;
}

int main(void)
{
	
	ledInit();
	
	cli();
	
	hal_USART_RxEnable();
	hal_USART_TxEnable();
	hal_USART_setCharSize(charSize_8BIT);
	hal_USART_setBaudRate(9600);
	hal_USART_registerRxCallback(rxCallback);
	sei();
	
	#if HUMAN_READABLE
    hal_USART_puts("\n\r>>");
	#endif
	
	while (1) 
    {
		parser();
    }
}

