#include "bind.h"

#include <curl/curl.h>

#define _str(...) #__VA_ARGS__
#define _e_tag "(native-bind " __FILE__ ":" _str(__LINE__) ") "

static size_t
buffer_string
(	char*  ptr,
	size_t size,
	size_t nmemb,
	void*  dest
) {
	luaL_Buffer* const data = dest;
	luaL_addlstring(data, ptr, size*nmemb);
	return size*nmemb;
}

_luafn(fetchURI) {
	const char* p_uri = luaL_checkstring(l,1);

	CURL* h = curl_easy_init();
	if (!h) {
		lua_pushstring(l, _e_tag "libcurl failed to init");
		lua_error(l);
	}

// 	int unwind = lua_gettop(l);
	luaL_Buffer download;
	luaL_buffinit(l, &download);

	char ebuf [CURL_ERROR_SIZE];
	curl_easy_setopt(h, CURLOPT_URL,           p_uri);
	curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, buffer_string);
	curl_easy_setopt(h, CURLOPT_WRITEDATA,     &download);
	curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION,true);
	curl_easy_setopt(h, CURLOPT_ERRORBUFFER,   ebuf);

	CURLcode e = curl_easy_perform(h);
	if (e == 0) {
		curl_easy_cleanup(h);
		luaL_pushresult(&download);
		return 1;
	} else {
// 		lua_settop(l,unwind);
		lua_pushnil(l);
		lua_pushstring(l, ebuf);
		return 2;
	}
}

_luaAPI(net,
  _export(fetchURI));