/***************************************************************************
*   Copyright (C) 2006 by Ian Reinhart Geiser   *
*   geiseri@sourcextreme.com   *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU Library General Public License as       *
*   published by the Free Software Foundation; either version 2 of the    *
*   License, or (at your option) any later version.                       *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU Library General Public     *
*   License along with this program; if not, write to the                 *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
#include "messageparser.h"
#include <QTime>

namespace KRPC
{

}

KRPC::MessageParser::MessageParser(QIODevice *device)
	: QObject(device), m_device(device)
{

}


KRPC::MessageParser::~MessageParser()
{
}

int KRPC::MessageParser::readMessage( )
{
	QTime timer;
	int delimiterCount = 0;
	int contentSize = 0;
	if( m_device->isReadable() )
	{
		m_device->waitForReadyRead(50);
		if( m_device->canReadLine() )
		{
			timer.start();
			QByteArray buffer;
			while( timer.elapsed( ) < 200 && delimiterCount != 1 )
			{
				if( m_device->canReadLine() )
				{
					QByteArray line = m_device->readLine();
					if( line == "\r\n")
						delimiterCount++;
					buffer += line;

					if( delimiterCount == 1 )
					{
						m_requestHeader = QHttpRequestHeader( buffer );
						contentSize = m_requestHeader.value("content-length").toInt();
					}
					timer.restart();
				}
				m_device->waitForReadyRead(50);
			}
			buffer.clear();
			while( timer.elapsed( ) < 200 && buffer.size() < contentSize )
			{
				if( m_device->bytesAvailable() > 0 )
				{
					buffer += m_device->readAll();
					timer.restart();
				}
				m_device->waitForReadyRead(50);
			}

			m_content = buffer;
			return m_content.size();

		}
		else
			return -1;
	}
	else
		return -2;
}

QHttpRequestHeader KRPC::MessageParser::requestHeader( ) const
{
	return m_requestHeader;
}

QByteArray KRPC::MessageParser::content( ) const
{
	return m_content;
}


