//
// C++ Implementation: urlfetch
//
// Description: 
//
//
// Author: Ian Reinhart Geiser <igeiser@devonit.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "urlfetch.h"

#include <QFile>
#include <qdebug.h>

URLFetch::URLFetch( const QUrl &url,  QObject *parent)
 : QObject(parent)
{
	QHttp *http = new QHttp( this );
	m_localLoop = new QEventLoop(this);
	m_responseBuffer = new QBuffer(this);
	if( !url.userName().isNull() )
		http->setUser( url.userName(), url.password() );
 	http->setHost( url.host(), url.port(80) );

	connect( http, SIGNAL(requestFinished( int, bool )), this, SLOT(handleRequestFinished(int,bool)));

	m_currentRequest = http->get( url.toEncoded(), m_responseBuffer );
}


URLFetch::~URLFetch()
{
}

QByteArray URLFetch::fetch(const QString & urlText, const QString &baseUrl)
{
	QUrl url( urlText );
	if( ( url.scheme().isEmpty() && baseUrl.isEmpty() ) || url.scheme() == "file" )
	{
		QFile file( url.path() );
		if( file.open( QIODevice::ReadOnly ) )
		{
			return file.readAll();
		}
		else
		{
			qDebug("Could not open %s", qPrintable( file.fileName() ) );
			return QByteArray();
		}
	}
	else
	{
		url = QUrl( baseUrl ).resolved(url);
		URLFetch fetchUrl( url );
		fetchUrl.m_localLoop->exec();
		return fetchUrl.m_responseBuffer->data();
	}
}


void URLFetch::handleRequestFinished(int id, bool error)
{
	QHttp *http = qobject_cast<QHttp*> ( sender() );
	if( m_currentRequest == id )
		m_localLoop->quit();
	if( error )
		qDebug("Error %s", qPrintable( http->errorString() ));
}



