#include <bsp.h>
#include <drvmsg.h>
#include "postif_proc.h"
#include "post_queue.h"


PostQueue::PostQueue()
{
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]++%s()\n\r"), _T(__FUNCTION__)));
    front = MAX_Q_NUMBER;
    rear = MAX_Q_NUMBER;
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]--%s()\n\r"), _T(__FUNCTION__)));
}

bool PostQueue::IsEmpty()
{
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]++%s()\n\r"), _T(__FUNCTION__)));

    if (rear == front)
    {
        DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]--%s is empty()\n\r"), _T(__FUNCTION__)));
        return true;
    }
    else
    {
        DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]--%s is not empty()\n\r"), _T(__FUNCTION__)));

        return false;
    }
}

bool PostQueue::IsFull()
{
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]++%s()\n\r"), _T(__FUNCTION__)));

    if ( (rear+1)%(MAX_Q_NUMBER+1) == front)
        return true;
    else
        return false;

}

bool PostQueue::Enqueue(PostProcContext *pCtxt)
{
    DBGMSG(0 ,(_T("[POST:CQ]++%s() Ctxt = 0x%x\n\r"), _T(__FUNCTION__),pCtxt));

    if(pCtxt->bPostInQueue)
    {
        DBGMSG(1 ,(_T("[POST:CQ]++%s() Ctxt = 0x%x is in QUEUE so return FALSE\n\r"), _T(__FUNCTION__),pCtxt));
        return false;
    }

    if(!(IsFull()))
    {
        rear = ++rear%(MAX_Q_NUMBER+1);
        //strcpy(passengers[rear].name, p.name);
        m_PostCtxt[rear] = pCtxt;
        pCtxt->bPostInQueue = TRUE;
    }
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]--%s() rear = %d front = %d, Ctxt = 0x%x\n\r"), _T(__FUNCTION__),rear,front,m_PostCtxt[rear] ));
    return true;
}

PostProcContext* PostQueue::Front()
{
    DBGMSG(POST_FUNC && POST_USR4 ,(_T("[POST:CQ]++%s()\n\r"), _T(__FUNCTION__)));
    PostProcContext *Ctxt = m_PostCtxt[(front+1)%(MAX_Q_NUMBER+1)];
    DBGMSG(POST_FUNC && POST_USR4 ,(_T("[POST:CQ]--%s() front Ctxt = 0x%x\n\r"), _T(__FUNCTION__),Ctxt));
    return Ctxt;
}

void PostQueue::Dequeue()
{
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]++%s()\n\r"), _T(__FUNCTION__)));

    if(!(IsEmpty()))
    {
        PostProcContext *Ctxt = m_PostCtxt[(front+1)%(MAX_Q_NUMBER+1)];

        DBGMSG(0 ,(_T("[POST:CQ]++%s() Ctxt = 0x%x\n\r"), _T(__FUNCTION__),Ctxt));

        Ctxt->bPostInQueue = FALSE;
        front = ++front%(MAX_Q_NUMBER+1);
    }
    DBGMSG(POST_FUNC && POST_USR3 ,(_T("[POST:CQ]--%s() rear = %d front = %d\n\r"), _T(__FUNCTION__),rear,front));
}



