#include "NetTools.h"
#include "Dialogs.h"

// download a file from url
String NetTools::Download(String const &url, uint32_t timeout, Event<int, int> progress)
{
	HttpRequest http;
	http.Url(url);
	http.RequestTimeout(timeout);
	http.MaxContentSize(1000000000);
	
	// execute till finished
	http.New();
	while(http.Do() && !http.IsTimeout() && !http.IsError())
	{
		int len =  http.GetContentLength();
		int div = (len > 10000 ? 1000 : 1);
		if(len)
			progress(http.GetContent().GetCount() / div, len / div);
	}
	if(http.IsError())
	{
		RLOG(http.GetErrorDesc());
		return "";
	}

	// return result
	String content = http.GetContent();
	if(content.IsVoid())
		return "";
	return content;
}

// download a file with a progress meter popup
String NetTools::Download(String const &prompt, String const &url, uint32_t timeout)
{
	ProgressPopup progress(prompt);
	progress.Show();
	String res = Download(url, timeout, progress.GetEventCb());
	progress.Hide();
	return res;
}
