#include "shell_port.h"
#include "shell.h"
#include "cola_device.h"
#include "cola_os.h"
#include <stdio.h>
#include "stdarg.h"

#define SHELL_MAX_CNT   512
Shell shell;
char shell_buffer[SHELL_MAX_CNT];
extern uint8_t RX_buffer[256];
extern uint8_t bufferIdx;

static cola_device_t *pDevDbgUart = NULL;
static task_t s_shell_task;

#define logPrintln(format, ...) \
    logWrite(LOG_NONE, format "\r\n", ##__VA_ARGS__)

static void bsp_dbg_uart_open(void)
{
	pDevDbgUart = cola_device_find("dbg_uart");
	if (pDevDbgUart)
		cola_device_open(pDevDbgUart, 0);
}

signed short User_Shell_Write(char *pBuf, unsigned short len)
{
	cola_device_write(pDevDbgUart,0,pBuf,len);
    return 0;
}


void logWrite(const char *fmt, ...)
{
	#define     LOG_BUFFER_SIZE    256
	static char logBuffer[LOG_BUFFER_SIZE];
    va_list vargs;
    int len;

    va_start(vargs, fmt);
    len = vsnprintf(logBuffer, LOG_BUFFER_SIZE - 1, fmt, vargs);
    va_end(vargs);

    if (len > LOG_BUFFER_SIZE)
    {
        len = LOG_BUFFER_SIZE;
    }

    User_Shell_Write(logBuffer, len);
}


void User_Shell_Read(void)
{
	uint8_t rxData;
	cola_device_read(pDevDbgUart,0,&rxData,1);
//	if(cola_device_read(pDevDbgUart,0,&rxData,1) > 0)
//		shellHandler(&shell,&rxData);
}
void User_Shell_Read_to_out(void *arg, uint32_t event)
{
	static int old_idx = 0;
	if(bufferIdx != old_idx)
	{
		shellHandler(&shell,RX_buffer[bufferIdx-1]);
		old_idx = bufferIdx;
	}

//	if(cola_device_read(pDevDbgUart,0,&rxData,1) > 0)
//		shellHandler(&shell,&rxData);
}
void fml_shell_init(void)
{
	bsp_dbg_uart_open();
    shell.write = User_Shell_Write;
    shellInit(&shell,shell_buffer,SHELL_MAX_CNT);
    User_Shell_Read();
#if 1
    cola_timer_create(&s_shell_task, User_Shell_Read_to_out, NULL);
	cola_timer_start(&s_shell_task, EN_COLA_TIMER_ALWAYS, 5);
#endif
}

//main函数形式
int func(int argc,char *argv[])
{
    printf("total parameters:%d\r\n",argc);
    for(char i = 1; i < argc; i++)
        printf("%s\r\n",argv[i]);
    return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN),func,func,test);

//普通C函数形式
int func1(int i,char ch,char *str)
{
    printf("input int: %d, char: %c, string: %s\r\n",i, ch, str);
    return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),func1,func1,test);

//导出变量
int varInt = 1986;
SHELL_EXPORT_VAR(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_VAR_INT),varInt,&varInt,test);

char str[] = "test string";
SHELL_EXPORT_VAR(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_VAR_STRING),varStr,str,test);
