package com.goafanti.crawler.callback;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.util.EntityUtils;

import com.goafanti.common.utils.LoggerUtils;

public abstract class CrawlerFutureCallback implements FutureCallback<HttpResponse> {

	private CountDownLatch		countDownLatch	= null;

	private Map<String, String>	result			= null;

	@Override
	public void completed(HttpResponse response) {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			try {
				handleWebpage(EntityUtils.toString(entity, "UTF-8"));
			} catch (Exception e) {
				LoggerUtils.error(getClass(), e.getMessage(), e);
			}
		}
		countDown();
	}

	@Override
	public void failed(Exception e) {
		countDown();
	}

	@Override
	public void cancelled() {
		countDown();
	}

	protected void handleWebpage(String pageContent) {

	}

	private void countDown() {
		if (countDownLatch != null) {
			countDownLatch.countDown();
		}
	}

	public void setCountDownLatch(CountDownLatch countDownLatch) {
		this.countDownLatch = countDownLatch;
	}

	public Map<String, String> getResult() {
		return result;
	}

	public void setResult(Map<String, String> result) {
		this.result = result;
	}

}
