/**
 * @file            log_rtt.c
 * @brief           Legacy log_rtt compatibility wrapper over mx_log
 */

#include "log_rtt.h"
#include "mx_log.h"

#include <stdarg.h>
#include <stdio.h>

#if MX_LOG_BACKEND_RTT
#include "SEGGER_RTT.h"
#endif

static mx_log_level_t log_rtt_to_mx_level(log_level_t lvl)
{
    switch (lvl) {
    case LOG_LVL_ERROR:
        return MX_LOG_LEVEL_ERROR;
    case LOG_LVL_WARN:
        return MX_LOG_LEVEL_WARN;
    case LOG_LVL_INFO:
        return MX_LOG_LEVEL_INFO;
    case LOG_LVL_DEBUG:
    default:
        return MX_LOG_LEVEL_DEBUG;
    }
}

void log_rtt_set_level(log_level_t lvl)
{
    mx_log_set_level(log_rtt_to_mx_level(lvl));
}

void log_rtt_printf(log_level_t lvl, const char *tag, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    mx_log_vprintf(log_rtt_to_mx_level(lvl), tag, fmt, ap);
    va_end(ap);
}

void log_hex_frame(const char *tag, const uint8_t *data, uint16_t len)
{
    mx_log_hex_frame(tag, data, len);
}

void log_rtt_init(void)
{
    mx_log_init();
}

#if MX_LOG_BACKEND_RTT
/* Keep legacy printf redirection behavior only when RTT backend is enabled. */
int fputc(int ch, FILE *f)
{
    (void)f;
    {
        char c = (char)ch;
        SEGGER_RTT_Write(0, &c, 1);
    }
    return ch;
}
#endif

