#include "sdolist.h"

#include <iostream.h>

ClassImp(PendingSDO);
ClassImp(PendingSDOList);

PendingSDOList::PendingSDOList()
{
    fFirst = new PendingSDO;
    fLast  = fFirst;
}

PendingSDOList::~PendingSDOList()
{
    DelAll();
    delete fFirst;
}

void PendingSDOList::DelAll()
{
    fMux.Lock();

    PendingSDO *prev = fFirst;
    PendingSDO *sdo;

    do
    {
        sdo = prev->Next;
        delete prev;

    } while((prev=sdo));

    fFirst = new PendingSDO;
    fLast  = fFirst;

    fMux.UnLock();
}

void PendingSDOList::Add(BYTE_t node, WORD_t idx, BYTE_t subidx)
{
    PendingSDO *sdo = fFirst;

    fMux.Lock();
    while ((sdo=sdo->Next))
        if (sdo->Node==node && sdo->Idx==idx && sdo->Subidx==subidx)
        {
            cout << "Warning: SDO Node #" << dec << (int)node << ", 0x";
            cout << hex << idx << "/" << (int)subidx;
            cout << " still pending." << endl;
            break;
        }

    fLast->Next = new PendingSDO(node, idx, subidx);
    fLast = fLast->Next;
    fMux.UnLock();
}

void PendingSDOList::Del(BYTE_t node, WORD_t idx, BYTE_t subidx)
{
    PendingSDO *prev = fFirst;
    PendingSDO *sdo;

    fMux.Lock();
    while ((sdo=prev->Next))
    {
        if (sdo->Node!=node || sdo->Idx!=idx || sdo->Subidx!=subidx)
        {
            prev = sdo;
            continue;
        }

        prev->Next = sdo->Next;

        delete sdo;

        if (!prev->Next)
            fLast = prev;

        break;
    }
    fMux.UnLock();
}

int PendingSDOList::IsPending() const
{
    return (int)fFirst->Next;
}

int PendingSDOList::IsPending(BYTE_t node)
{
    int rc = FALSE;
    PendingSDO *sdo = fFirst;

    fMux.Lock();
    while ((sdo=sdo->Next))
        if (sdo->Node==node)
        {
            rc = TRUE;
            break;
        }
    fMux.UnLock();

    return rc;
}

int PendingSDOList::IsPending(BYTE_t node, WORD_t idx, BYTE_t subidx)
{
    int rc = FALSE;
    PendingSDO *sdo = fFirst;

    fMux.Lock();
    while ((sdo=sdo->Next))
        if (sdo->Node==node && sdo->Idx==idx && sdo->Subidx==subidx)
        {
            rc = TRUE;
            break;
        }
    fMux.UnLock();

    return rc;
}
