/*******************************************************************************
 *	BUrl.cpp	BEAM BUrl access class
 *			T.Barnaby,	BEAM Ltd,	12/11/02
 *******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <BUrl.h>
#include <curl/curl.h>

int BUrl::oinit;

size_t BUrl::writeData(void* data, size_t size, size_t elSize, void* stream){
	BUrl*	o = (BUrl*)stream;
	char	buf[4096];
	uint	n = size * elSize;
	
	if(n > (sizeof(buf) - 1))
		n = sizeof(buf) - 1;
	
	memcpy(buf, data, n);
	buf[n] = '\0';

	o->ores	= o->ores + buf;
	return n;
	
}

BUrl::BUrl(){
	if(!oinit)
		curl_global_init(CURL_GLOBAL_NOTHING);
	oinit++;
}

BUrl::~BUrl(){
	oinit--;
	if(!oinit)
		curl_global_cleanup();
}

BError BUrl::readString(BString url, BString& str){
	BError		err;
	CURLcode	r;
	CURL*		c;
	
	ores = "";
	c = curl_easy_init();
	if(r = curl_easy_setopt(c, CURLOPT_URL, url.retStr()))
		return BError(1, "Error setting URL");
		
	curl_easy_setopt(c, CURLOPT_FILE, this);
	curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, writeData);

	if(r = curl_easy_perform(c))
		err.set(ErrorMisc, BString("Unable to read URL: ") + url);

	curl_easy_cleanup(c);
	str = ores;
	return err;
}
