/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.fw.cache;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import gov.va.med.fw.security.SecurityContextHelper;
import gov.va.med.fw.service.trigger.TriggerEvent;

/**
 * Initial javadoc for class TriggerEventCacheManager.
 * TODO - Add content here
 * 
 * Created Nov 3, 2005 12:29:09 PM
 * @author DNS   BOHMEG
 */
public class TriggerEventCacheManager extends AbstractCacheManager {
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -4370803641246991293L;
	public static final String TRIGGER_EVENTS_KEY = TriggerEventCacheManager.class.getName() + ".TRIGGER_EVENTS";
	
	
	/**
	 * A default constructor
	 */
	public TriggerEventCacheManager() {
		super();
	}

	/** Stores created (but not yet routed) TriggerEvents to thread bound storage */
	public void storeTriggerEvents(Set triggerEvents) {
		Iterator itr = triggerEvents != null ? triggerEvents.iterator() : null;
		Set cachedEvents = null; // ensures no duplicates
		TriggerEvent event = null;
		while(itr != null && itr.hasNext()) {
			try {
				event = (TriggerEvent) itr.next();
				synchronized(this) {
					cachedEvents = (Set) getItem(TRIGGER_EVENTS_KEY);
					if(cachedEvents == null) {
						cachedEvents = new HashSet();
						cacheItem(TRIGGER_EVENTS_KEY, cachedEvents);
					}
				}
				// set initiater on TriggerEvent
				event.setInitiater(SecurityContextHelper
						.getSecurityContext().getUserPrincipal()
						.getUserCredentials());
				
				cachedEvents.add(event);
			} catch(ClassCastException e) {
				throw new IllegalArgumentException("Expected object of type TriggerEvent");
			}			
		}
	}
	
	/** Removes any TriggerEvent's bound to Thread */
	public Set removeTriggerEvents() {
		return (Set) removeItem(TRIGGER_EVENTS_KEY);
	}
	
	public boolean hasTriggerEvents() {
		return containsItem(TRIGGER_EVENTS_KEY);
	}
	
	public Set getTriggerEvents() {
		return (Set) getItem(TRIGGER_EVENTS_KEY);
	}	
}
