
#include "RexIExternalChannel.h"
//## dependency RexExternalChannelMessageDescriptor
//#include "RexExternalChannelMessageDescriptor.h"
//## dependency RexIEternalChannelReceiver
//#include "RexIEternalChannelReceiver.h"
//## package Rex::RexPackages::RexNetPkg

//## class RexIExternalChannel
RexIExternalChannel::RexIExternalChannel() : received(0), unserved(0), rxPeriodMs(0), missed(0), tx_stored_buffer(0), tx_stored_len(0), chId(0, 0)
{
    //#[ operation RexIExternalChannel()
    //#]
}

RexIExternalChannel::RexIExternalChannel(const RexExternalChannelId& id) : received(0), unserved(0), rxPeriodMs(0), missed(0), tx_stored_buffer(0), tx_stored_len(0), chId(id),
 m_receiver(0)
{
    //#[ operation RexIExternalChannel(RexExternalChannelId)
    //#]
}

RexIExternalChannel::~RexIExternalChannel()
{
}

void RexIExternalChannel::attachReceiver(RexIEternalChannelReceiver& receiver)
{
    //#[ operation attachReceiver(RexIEternalChannelReceiver)
    m_receiver=&receiver;
    //#]
}

const RexExternalChannelId& RexIExternalChannel::id() const
{
    //#[ operation id() const
    return chId;
    //#]
}

void RexIExternalChannel::releaseMessage(const RexExternalChannelMessageDescriptor& d)
{
    //#[ operation releaseMessage(RexExternalChannelMessageDescriptor)
    (void)d;

    //#]
}

void RexIExternalChannel::resend()
{
    //#[ operation resend()
    if (tx_stored_buffer && tx_stored_len)
        send(tx_stored_buffer, tx_stored_len);


    //#]
}

void RexIExternalChannel::dispatch(const void* data, unsigned long size_bytes, const RexIExternalChannel::time_t& timetag)
{
#if 0
    //#[ operation dispatch(const void*,unsigned long,time_t)
    ++received;

    RexTimetag::Elapsed period=timetag.timetag()-itsRexBatchTag.timetag();
    rxPeriodMs=period.getValue();

    RexExternalChannelMessageDescriptor d(this, data, size_bytes);

    bool auto_release=true;

    if (m_receiver)
    {
        auto_release=m_receiver->onRexExternalChannelReceive(d);
        if (auto_release)
            releaseMessage(d);
    }
    else
        ++unserved;

    if (auto_release)
        releaseMessage(d);


#endif

    //#]
}

unsigned long RexIExternalChannel::getReceived() const
{
    return received;
}

int RexIExternalChannel::getUnserved() const
{
    return unserved;
}

unsigned long RexIExternalChannel::getRxPeriodMs() const
{
    return rxPeriodMs;
}

unsigned long RexIExternalChannel::getMissed() const
{
    return missed;
}

RexIExternalChannel::time_t RexIExternalChannel::getLastRxTime() const
{
    return lastRxTime;
}

RexBatchTag* RexIExternalChannel::getItsRexBatchTag() const
{
    return (RexBatchTag*) &itsRexBatchTag;
}
