#include "NULLSink.h"

#include <GroupsockHelper.hh>

CNULLSink* CNULLSink::createNew(UsageEnvironment& env) {
    return new CNULLSink(env);
}

CNULLSink::CNULLSink(UsageEnvironment& env)
    : MediaSink(env){
    fMaxPayloadSize = 2000 * 1024;
    fOutputBuffer = new unsigned char[fMaxPayloadSize];
}

CNULLSink::~CNULLSink() {
    int a;
    a++;
    delete[] fOutputBuffer;
}

Boolean CNULLSink::continuePlaying() {
    gettimeofday(&fNextSendTime, NULL);

    continuePlaying1();
    return True;
}

void CNULLSink::continuePlaying1() {
    nextTask() = NULL;
    if (fSource != NULL) {
        fSource->getNextFrame(fOutputBuffer, fMaxPayloadSize,
                              afterGettingFrame, this,
                              onSourceClosure, this);
    }
}

void CNULLSink::afterGettingFrame(void* clientData, unsigned frameSize,
                                     unsigned numTruncatedBytes,
                                     struct timeval /*presentationTime*/,
                                     unsigned durationInMicroseconds) {
    CNULLSink* sink = (CNULLSink*)clientData;
    sink->afterGettingFrame1(frameSize, numTruncatedBytes, durationInMicroseconds);
}

void CNULLSink::afterGettingFrame1(unsigned frameSize, unsigned numTruncatedBytes,
                                      unsigned durationInMicroseconds) {
    fNextSendTime.tv_usec += durationInMicroseconds;
    fNextSendTime.tv_sec += fNextSendTime.tv_usec/1000000;
    fNextSendTime.tv_usec %= 1000000;

    struct timeval timeNow;
    gettimeofday(&timeNow, NULL);
    int secsDiff = fNextSendTime.tv_sec - timeNow.tv_sec;
    int64_t uSecondsToGo = secsDiff*1000000 + (fNextSendTime.tv_usec - timeNow.tv_usec);
    if (uSecondsToGo < 0 || secsDiff < 0) { // sanity check: Make sure that the time-to-delay is non-negative:
        uSecondsToGo = 0;
    }

    nextTask() = envir().taskScheduler().scheduleDelayedTask(uSecondsToGo,
                                                             (TaskFunc*)sendNext, this);
}

void CNULLSink::sendNext(void* firstArg) {
    CNULLSink* sink = (CNULLSink*)firstArg;
    sink->continuePlaying1();
}
