package com.goafanti.crawler;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.reactor.ConnectingIOReactor;

import com.goafanti.crawler.callback.CrawlerFutureCallback;

public class RequestUtils {

	public static void startRequest(String url, CrawlerFutureCallback callback) throws Exception {
		CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		CountDownLatch latch = new CountDownLatch(1);
		callback.setCountDownLatch(latch);
		httpclient.execute(buildGetRequest(url), callback);
		latch.await();
		httpclient.close();
	}

	public static void startRequest(Map<String, CrawlerFutureCallback> requests) throws Exception {
		if (requests.isEmpty()) {
			return;
		}
		ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
		PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
		cm.setMaxTotal(10);
		CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(cm).build();
		httpclient.start();
		CountDownLatch latch = new CountDownLatch(requests.size());
		CrawlerFutureCallback cb = null;
		for (String key : requests.keySet()) {
			cb = requests.get(key);
			cb.setCountDownLatch(latch);
			httpclient.execute(buildGetRequest(key), cb);
		}
		latch.await();
		httpclient.close();
	}

	private static HttpGet buildGetRequest(String url) {
		HttpGet request = new HttpGet(url);

		request.setConfig(RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000)
				.setSocketTimeout(1000).build());

		request.setHeader("User-Agent",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
		return request;
	}
}
