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

static_fifo_declare(uart_char_fifo, 256, unsigned char, char);
extern int sendchar(int ch);
extern bool network_write_char(const char c);
extern bool network_write_string(const char *str, size_t size);
extern tls_os_task_t nano_shell_task_handle;

s16 uart0_rx_callback(u16 len, void *user_data)
{
    (void)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]);
    }
        
    (void)tls_os_task_resume_from_isr(nano_shell_task_handle);
    return 0;
}

s16 uart1_rx_callback(u16 len, void *user_data)
{
    (void)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]);
    }

    (void)tls_os_task_resume_from_isr(nano_shell_task_handle);
    return 0;
}

void network_rx_callback(u16 len, char *data)
{
    if(!len)return;
    
    for(int i = 0; i < len; i++)
    {
        fifo_push(uart_char_fifo, data[i]);
    }

    (void)tls_os_task_resume(nano_shell_task_handle);
}

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;
}

int shell_printf(const char *format, ...)
{
    static char shell_printf_buffer[CONFIG_SHELL_PRINTF_BUFFER_SIZE];

    int length = 0;

    va_list ap;
    va_start(ap, format);
    length = vsnprintf(shell_printf_buffer, CONFIG_SHELL_PRINTF_BUFFER_SIZE, format, ap);
    va_end(ap);

    (void)tls_uart_write(TLS_UART_0, shell_printf_buffer, length);
    (void)tls_uart_write(TLS_UART_1, shell_printf_buffer, length);
    (void)network_write_string(shell_printf_buffer, length);
    return length;
}

void shell_puts(const char *str)
{
    (void)shell_printf(str);
}

void shell_putc(char ch)
{
  (void)shell_printf("%c", ch);
}

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