#include "osal_mq.h"
#include "osal.h"
#include <rtthread.h>

osal_mq_t osal_mq_create(const char* name,
                        osal_size_t msg_size,
                        osal_size_t max_msgs)
{
    OSAL_ASSERT(name != NULL);
    OSAL_ASSERT(msg_size > 0);
    OSAL_ASSERT(max_msgs > 0);

    rt_mq_t mq;
    
    mq = rt_mq_create(name, msg_size, max_msgs, RT_IPC_FLAG_FIFO);
    
    return (osal_mq_t)mq;
}

osal_err_t osal_mq_delete(osal_mq_t mq)
{
    if (mq == NULL)
    {
        return OSAL_INVAL;
    }
    
    rt_err_t ret = rt_mq_delete((rt_mq_t)mq);
    
    return osal_get_errno(ret);
}

osal_err_t osal_mq_send(osal_mq_t mq, const void* buffer, osal_size_t size)
{
    if (mq == NULL || buffer == NULL)
    {
        return OSAL_INVAL;
    }
    
    rt_err_t ret = rt_mq_send((rt_mq_t)mq, (void*)buffer, size);
    
    return osal_get_errno(ret);
}

osal_err_t osal_mq_urgent(osal_mq_t mq, const void* buffer, osal_size_t size)
{
    if (mq == NULL || buffer == NULL)
    {
        return OSAL_INVAL;
    }
    
    rt_err_t ret = rt_mq_urgent((rt_mq_t)mq, (void*)buffer, size);
    
    return osal_get_errno(ret);
}

osal_err_t osal_mq_recv(osal_mq_t mq, void* buffer, osal_size_t size, osal_int32_t timeout)
{
    if (mq == NULL || buffer == NULL)
    {
        return OSAL_INVAL;
    }
    
    rt_err_t ret = rt_mq_recv((rt_mq_t)mq, buffer, size, timeout);
    
    return osal_get_errno(ret);
}
