#include "bytereader.h"
#include <QFinalState>

ByteReader::ByteReader(QIODevice *device, QState *parent ) :
    QState(parent), m_device(device), m_buffer(0), m_length(0), m_offset(0), m_hasError(false)
{
    QState *readNextBytes = new QState(this);
    QFinalState *done = new QFinalState(this);
    QFinalState *error = new QFinalState(this);

    readNextBytes->addTransition(m_device, SIGNAL(readyRead()), readNextBytes );
    readNextBytes->addTransition(this, SIGNAL(readDone()), done );
    readNextBytes->addTransition(this, SIGNAL(readError()), error );

    connect( readNextBytes, SIGNAL(entered()), this, SLOT(onReadNextBytes()));
    connect( done, SIGNAL(entered()), this, SLOT(onDone()));
    connect( error, SIGNAL(entered()), this, SLOT(onError()));

    setInitialState(readNextBytes);
}

void ByteReader::configure(char *buffer, quint32 len)
{
    m_buffer = buffer;
    m_length = len;
}

bool ByteReader::hasError() const
{
    return m_hasError;
}

void ByteReader::onReadNextBytes()
{
    m_offset += m_device->read( m_buffer + m_offset, m_length - m_offset );
    if( m_offset == m_length )
        emit readDone();
}

void ByteReader::onError()
{
    m_hasError = true;
}

void ByteReader::onDone()
{

}

