/**
 *
 */
package eu.dnetlib.common.profile;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.rmi.enabling.ISLookUpDocumentNotFoundException;
import eu.dnetlib.rmi.enabling.ISLookUpException;
import eu.dnetlib.rmi.enabling.ISLookUpService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author jochen
 */
public class ResourceCache implements IResourceDaoSupport {

	private final LoadingCache<String, Resource> cache;

	@Autowired
	private UniqueServiceLocator serviceLocator;

	public ResourceCache() {
		cache = CacheBuilder.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build(new CacheLoader<String, Resource>() {

			@Override
			public Resource load(String aKey) throws Exception {
				Resource resource = null;
				if (aKey.startsWith("collection")) {
					return new Resource(byQuery(aKey));
				} else {
					return new Resource(byId(aKey));
				}
			}

			private String byQuery(String aQuery) throws ISLookUpDocumentNotFoundException, ISLookUpException {
				return serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(aQuery);
			}

			private String byId(String aId) throws ISLookUpDocumentNotFoundException, ISLookUpException {
				return serviceLocator.getService(ISLookUpService.class).getResourceProfile(aId);
			}

		});
	}

	@Override
	public List<Resource> getResources(String xquery) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Resource getResourceByXquery(String xquery) throws Exception {
		return cache.get(xquery);
	}

	@Override
	public Resource getResource(String id) throws Exception {
		return cache.get(id);
	}

	@Override
	public void updateResource(String id, Resource resource) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeResource(String id, Resource resource) {
		// TODO Auto-generated method stub

	}

}
