#include "QrfeFifo.h"

#include <QTimer>

QrfeFifo::QrfeFifo(QObject *parent) :
    QIODevice(parent)
{
	m_mutex = new QMutex(QMutex::Recursive);
}

QrfeFifo::~QrfeFifo()
{
	delete m_mutex;
}

bool QrfeFifo::open ( OpenMode mode )
{
    return QIODevice::open(mode | QIODevice::Unbuffered);
}

bool QrfeFifo::reset ()
{
    QMutexLocker lock(m_mutex);
    m_buffer.clear();

    return true;
}

qint64 QrfeFifo::bytesAvailable () const
{
	QMutexLocker lock(m_mutex);
	qint64 ret = m_buffer.size();

    return ret;
}

quint64 QrfeFifo::prepend ( const QByteArray& data )
{
    QMutexLocker lock(m_mutex);
    m_buffer.prepend(data);

    return data.size();
}

qint64 QrfeFifo::readData ( char * data, qint64 maxSize )
{
	QMutexLocker lock(m_mutex);
	qint64 size = qMin(maxSize, (qint64)m_buffer.size());
	if(size > 0)
	{
		memcpy(data, m_buffer.data(), size);
		m_buffer.remove(0, size);
	}

	return size;
}

qint64 QrfeFifo::writeData ( const char * data, qint64 maxSize )
{
	m_mutex->lock();;
	m_buffer.append(data, maxSize);
	m_mutex->unlock();

	//emit readyRead();
	QMetaObject::invokeMethod(this, "_q_emitSignals", Qt::QueuedConnection);

	return maxSize;
}

void QrfeFifo::_q_emitSignals()
{
	emit readyRead();
}
