#include "uart_log.h"
#include "stdarg.h"
#include "string.h"

UART_HandleTypeDef *console = NULL;
extern UART_HandleTypeDef UartHandle;

int putchar(int c)
{
    if (console == NULL) {
        return 0;
    }

    HAL_UART_Transmit(console, (uint8_t*)&c, 0, HAL_TIMEOUT_VALUE);

    return c;
}

int puts(const char *c)
{
    int len;

    len = strlen(c);

    if (console == NULL) {
        return 0;
    }

    HAL_UART_Transmit(console, (uint8_t*)c, len, HAL_TIMEOUT_VALUE);

    return len;
}

int putstring(const char *c)
{
    int len;

    if (c == NULL) {
        return 0;
    }

    len = strlen(c);

    if (console == NULL) {
        return 0;
    }

    HAL_UART_Transmit(console, (uint8_t*)c, len, HAL_TIMEOUT_VALUE);

    return len;
}

#if defined(CONFIG_VSNPRINTF_NANO) && CONFIG_VSNPRINTF_NANO
int printf(const char *fmt, ...)
{
    char print_buf[512];
    int len;
    va_list ap;

    va_start(ap, fmt);
    len = vsnprintf(print_buf, sizeof(print_buf), fmt, ap);
    va_end(ap);

    len = (len > sizeof(print_buf)) ? sizeof(print_buf) : len;

    HAL_UART_Transmit(console, (uint8_t*)print_buf, len, HAL_TIMEOUT_VALUE);

    return len;
}
#else
extern int console_vsnprintf(const char *fmt, va_list args);
int printf(const char *fmt, ...)
{
    int len;
    va_list ap;

    va_start(ap, fmt);
    len = console_vsnprintf(fmt, ap);
    va_end(ap);

    return len;
}
#endif

void uart_log_set_console(void)
{
    console = &UartHandle;
}
