#include "URLFetcher.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <stdexcept>

char *URLFetcher::tmpdir(NULL);

URLFetcher::URLFetcher()
  : curlref(NULL)
{
	curlref = curl_easy_init();
	assert(curlref);
	if (!tmpdir)
	{
		tmpdir = mkdtemp(strdup("/tmp/goplay.thumb.XXXXXX"));
		assert(tmpdir);
	}
}

const std::string URLFetcher::get(const std::string url,
                                  const std::string basename)
{
	if (curlref)
	{
		curl_easy_setopt(curlref, CURLOPT_URL, url.c_str());
		std::string path(tmpdir);
		path += "/" + basename;
		FILE *output = fopen(path.c_str(), "w");
		curl_easy_setopt(curlref, CURLOPT_WRITEDATA, output);
		CURLcode res = curl_easy_perform(curlref);
		fflush(output);
		fclose(output);
		if (0 != res)
		{
			throw std::runtime_error(std::string("failed to fetch ") + url);
		}
		return path;
	}
	throw std::runtime_error(std::string("unable to fetch ") + url);
}

URLFetcher::~URLFetcher()
{
	curl_easy_cleanup(curlref);
}

#ifdef TEST
int main(int argc, char *argv[])
{
	URLFetcher fetcher;
	const std::string path =
	  fetcher.get(std::string("http://www.debian.org"),
		      std::string("index.html"));
	std::cout << path;
}
#endif
