package com.eactive.eai.common.ehcache;

import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.session.SessionManager;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.worker.Future;
import com.eactive.eai.common.worker.ResponseMap;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;

public class CustomRMICacheEventListener implements CacheEventListener {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static final CacheEventListener INSTANCE = new CustomRMICacheEventListener();

	@Override
	public void dispose() {
		// empty
	}

	@Override
	public void notifyElementEvicted(Ehcache cache, Element element) {
		// empty
	}

	@Override
	public void notifyElementExpired(Ehcache cache, Element element) {
		// empty
	}

	@Override
	public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
		logger.debug("CustomRMICacheEventListener] notifyElementPut : " + element );
		setEvent(cache, element);
	}

	@Override
	public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
		logger.debug("CustomRMICacheEventListener] notifyElementRemoved : " + element );
	}

	@Override
	public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
		logger.debug("CustomRMICacheEventListener] notifyElementUpdated : " + element );
		setEvent(cache, element);
	}

	@Override
	public void notifyRemoveAll(Ehcache cache) {
		// empty
	}

	@Override
	public Object clone() throws CloneNotSupportedException{
		throw new CloneNotSupportedException("Singleton instance");
	}

	private void setEvent(Ehcache cache, Element element){
		if (SessionManager.TOPIC_CAHCE_NAME.equals(cache.getName())){
			String guidKey = (String)element.getKey();
			EAIMessage data = (EAIMessage)element.getValue();
			logger.debug("CustomRMICacheEventListener] setEvent["+guidKey+"]");
			Future future = ResponseMap.getInstance().get(guidKey);
			if (future != null){
				logger.debug("CustomRMICacheEventListener] setEvent["+guidKey+"] put to Future");
				future.getSlot().put(data);
				cache.remove(guidKey);
			}
		}
	}
}
