#include "osp_type_def.h"
#include "err_num.h"
#include "osp_msg.h"
#include "osp_sw_queue.h"
#include "osp_sem.h"
#include "osp_task.h"

/*
    need lock

    事件入队后，唤醒相应的事件
*/

int osp_sw_queue_int(osp_sw_queue *p_sw_queue_head)
{
    p_sw_queue_head->enque_idx = 0;
    p_sw_queue_head->deque_idx = 0;
    p_sw_queue_head->deque_count = 0;
    p_sw_queue_head->enque_count = 0;
    p_sw_queue_head->full_count  = 0;
    p_sw_queue_head->empty_count = 0;
    p_sw_queue_head->mask = OSP_QUE_DEP-1;
    //p_sw_queue_head->msg_sem = osp_create_sem(1);
    /*if (NULL == p_sw_queue_head->msg_sem)
    {
        return -OSP_PAR_ILL;
    }*/
    return OSP_OK;
}

int osp_sw_enque(osp_msg_head *pmsg_head, osp_sw_queue *que)
{
    if (NULL == que)
    {
#ifdef OSP_DEBUG_TEST
        debug_write(OSP_DEBUG_POT(g_ape_id, 88), 0xffffffff);
#endif
        return -OSP_PAR_ILL;
    }

    /* 获取信号量 */
    //osp_wait_sem(que->msg_sem);

    if((que->enque_count - que->deque_count) >= OSP_QUE_DEP)
    {
        que->full_count++;
#ifdef OSP_DEBUG_TEST
        debug_write(OSP_DEBUG_POT(g_ape_id, 80), que->full_count);
#endif
        return -OSP_QUE_FULL;
    }

    que->que_msg[que->enque_idx] = pmsg_head;
    //memcpy((que->que_msg+(que->enque_idx)*OSP_QUE_SIZE), &pmsg_head, sizeof(osp_msg_head));
    que->enque_idx = (que->enque_idx +1)&(que->mask);
    que->enque_count++;
#ifdef UCP_OSP_DBG_ENABLE
    debug_write(OSP_DEBUG_POT(g_ape_id, 81), pmsg_head);
    debug_write(OSP_DEBUG_POT(g_ape_id, 82), que->enque_count);
    debug_write(OSP_DEBUG_POT(g_ape_id, 83), que->deque_count);
#endif

    //osp_post_sem(que->msg_sem);
    return OSP_OK;
}

int osp_sw_deque(osp_msg_head **pmsg_head, osp_sw_queue *que)
{
    if (NULL == que)
    {
        return -OSP_PAR_ILL;
    }

    /* 获取信号量 */
    //osp_wait_sem(que->msg_sem);

    if(que->enque_count == que->deque_count)
    {
        que->empty_count++;
#ifdef OSP_DEBUG_TEST
        debug_write(OSP_DEBUG_POT(g_ape_id, 84), que->empty_count);
#endif
        return -OSP_QUE_EMPT;
    }

    *pmsg_head = que->que_msg [que->deque_idx];
    //pmsg_head = (osp_msg_head*)(que->que_msg + ((que->deque_idx)*OSP_QUE_SIZE));
    que->deque_idx = (que->deque_idx+1)&(que->mask);
    que->deque_count++;

#ifdef UCP_OSP_DBG_ENABLE
    debug_write(OSP_DEBUG_POT(g_ape_id, 85), *pmsg_head);
    debug_write(OSP_DEBUG_POT(g_ape_id, 86), que->enque_count);
    debug_write(OSP_DEBUG_POT(g_ape_id, 87), que->deque_count);
#endif

    //osp_post_sem(que->msg_sem);
    return OSP_OK;
}

