package eu.dnetlib.data.utils;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

public class HttpFetcher {

	private static final Log log = LogFactory.getLog(HttpFetcher.class);

	private static final int INTERVAL_MILLIS = 20000;

	public static final int MAX_NUMBER_OF_ATTEMPTS = 10;

	public static String fetch(final String url, final String accessToken) throws URISyntaxException {
		return fetch(new URI(url), 1, accessToken);
	}

	public static String fetch(final URI url, final String accessToken) {
		return fetch(url, 1, accessToken);
	}

	public static String fetch(final URI url, final int attempts, final String accessToken) {
		if (attempts > MAX_NUMBER_OF_ATTEMPTS) {
			log.error("Max number of attempts reached, downloading url: " + url);
			return "";
		}

		try {
			log.debug("Downloading URL: " + url + " - try: " + attempts);

			final HttpHeaders headers = new HttpHeaders();
			if (StringUtils.isNotBlank(accessToken)) {
				log.debug("Perform call using access token: " + accessToken);
				headers.set("Authorization", "Bearer " + accessToken);
			}

			return RestTemplateFactory.newInstance()
					.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class)
					.getBody();
		} catch (final Throwable e) {
			try {
				log.error("Error downloading url: " + url + " - try: " + attempts + " - " + e.getMessage());
				Thread.sleep(INTERVAL_MILLIS);
				return fetch(url, attempts + 1, accessToken);
			} catch (final InterruptedException e1) {
				log.error(e);
				return "";
			}
		}
	}
}
