package eu.dnetlib.functionality.lightui.utils;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RepositoryImpl extends AbstractQuerable implements Repository {
	public static Log log = LogFactory.getLog(RepositoryImpl.class);

	private String iconUrl;
	private String url;

	private CachedImageDao cachedImageDao;

	public RepositoryImpl() {
		// dummy
	}
	
	public RepositoryImpl(String name) {
		// this(name,
		// "http://admin1.driver.research-infrastructures.eu/images/repositoryLogos/logo-boekentoren.png");
		this(name, null);
	}

	public RepositoryImpl(String name, String iconUrl) {
		this(name, iconUrl, null);
	}

	public RepositoryImpl(String name, String iconUrl, String url) {
		setName(name);
		setIconUrl(iconUrl);
		setUrl(url);
	}

	public String getQuery() {
		return "repositoryName = \"" + getName() + "\"";
	}

	private void setIconUrl(String iconUrl) {
		this.iconUrl = iconUrl;

	}

	public String getIconUrl() {

		if (cachedImageDao.getCachedImage(iconUrl) == null) {
			if("".equals(iconUrl))
				return "";
			
			HttpClient client = new HttpClient();
			HttpMethod method = new GetMethod(iconUrl);
			method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
					new DefaultHttpMethodRetryHandler(3, false));

			try {
				client.executeMethod(method);
				String contentType = method.getResponseHeaders("content-type")[0]
						.getValue();
				cachedImageDao.putCachedImage(iconUrl, new CachedImage(method
						.getResponseBody(), contentType));
			} catch (Exception e) {
				log.warn("Cannot cache image: " + iconUrl);
				e.printStackTrace();
			} finally {
				method.releaseConnection();
			}
		}

		return iconUrl;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public CachedImageDao getCachedImageDao() {
		return cachedImageDao;
	}

	public void setCachedImageDao(CachedImageDao cachedImageDao) {
		this.cachedImageDao = cachedImageDao;
	}

}
