package eu.dnetlib.functionality.lightui.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.data.information.publisher.rmi.PublisherService;
import eu.dnetlib.enabling.tools.ServiceLocator;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

public class CachingPublisherClientImpl implements CachingPublisherClient {

	protected Log log = LogFactory.getLog(CachingPublisherClientImpl.class);

	ServiceLocator<PublisherService> publisherLocator;


	private Cache recordCache;

	public String getResourceById(String id, String format) {
		log.debug("getting record by id from cache");
		Element element = recordCache.get(makeCacheKey(id, format));
		if(element == null) {
			String record = publisherLocator.getService().getResourceById(id, format);
			updateRecord(id, format, record);
			return record;
		}
		log.debug("found record in cache");
		return (String) element.getObjectValue();
	}

	public void updateRecord(String id, String format, String record) {
		log.debug("updating cache for " + id);
		recordCache.put(new Element(makeCacheKey(id, format), record));
	}

	protected String makeCacheKey(String id, String format) {
		return id + format;
	}

	public Cache getRecordCache() {
		return recordCache;
	}

	@Required
	public void setRecordCache(Cache recordCache) {
		this.recordCache = recordCache;
	}

	public ServiceLocator<PublisherService> getPublisherLocator() {
		return publisherLocator;
	}

	@Required
	public void setPublisherLocator(ServiceLocator<PublisherService> publisherLocator) {
		this.publisherLocator = publisherLocator;
	}
}
