#include "wm_include.h"
#include "shell_io/static_fifo.h"

static_fifo_declare(uart_char_fifo, 256, unsigned char, char);
extern int sendchar(int ch);
extern tls_os_task_t nano_shell_task_handle;

s16 uart0_rx_callback(u16 len, void *user_data)
{
    u8 buff[256] = "";
    int data_len = tls_uart_read(TLS_UART_0, (u8 *) buff, 256);
    for(int i = 0; i < data_len; i++)
    {
        fifo_push(uart_char_fifo, buff[i]);
    }
        
    tls_os_task_resume_from_isr(nano_shell_task_handle);
    return 0;
}

s16 uart1_rx_callback(u16 len, void *user_data)
{
    u8 buff[256] = "";
    int data_len = tls_uart_read(TLS_UART_1, (u8 *) buff, 256);
    for(int i = 0; i < data_len; i++)
    {
        fifo_push(uart_char_fifo, buff[i]);
    }

    tls_os_task_resume_from_isr(nano_shell_task_handle);
    return 0;
}

int shell_getc(char *ch)
{
    if(is_fifo_empty(uart_char_fifo))
    {
        //If the fifo is empty then we can suspend the task since
        //it is only waiting for inputs to be processed
        tls_os_task_suspend(NULL);
        return 0;
    }   

    *ch = fifo_pop_unsafe(uart_char_fifo); 
    return 1;
}

void low_level_write_char(char ch)
{
    (void)sendchar((int)ch);
    (void)tls_uart_write(TLS_UART_1, &ch, 1);
}
