#include <f4ll/console_handler.h>

#include <FreeRTOS.h>
#include <portmacro.h>

#include <thread_safe_console_output.h>

thread_safe_console_output::thread_safe_console_output(f4ll::console_handler &con)
    : m_con(con),
      m_sem(xSemaphoreCreateMutexStatic(&m_sem_buf))
{
}

thread_safe_console_output::size_type thread_safe_console_output::append(char const *s)
{
    xSemaphoreTake(m_sem, portMAX_DELAY);
    auto ret = m_con.append(s);
    xSemaphoreGive(m_sem);
    return ret;
}

void thread_safe_console_output::flush()
{
    xSemaphoreTake(m_sem, portMAX_DELAY);
    m_con.flush();
    xSemaphoreGive(m_sem);
}

void thread_safe_console_output::print(const char *s)
{
    xSemaphoreTake(m_sem, portMAX_DELAY);
    m_con.print(s);
    xSemaphoreGive(m_sem);
}
