package sfs.cluster.lobby;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Logger;

import sfs.cluster.lobby.data.ClusterEvent;
import sfs.cluster.lobby.handlers.cluster.IClusterEvtHandler;

/**
 * This class handles the cluster events
 * Uses a blocking queue for collecting the events and pool of worker threads to handle the jobs
 */
public class ClusterEventHandler implements Runnable
{
	boolean running = false;
	BlockingQueue<ClusterEvent> queue;
	AbstractExtension lobby;
	Map<String, IClusterEvtHandler> sfsClusterHandlers;
	Logger log;
	
	public ClusterEventHandler(AbstractExtension parentExtension, BlockingQueue<ClusterEvent> queue)
    {
		this.lobby = parentExtension;
	    this.queue = queue;
	    this.log = SmartFoxServer.log;
	    
	    sfsClusterHandlers = new HashMap<String, IClusterEvtHandler>();	    
    }
	
	
	public void run()
	{
		running = true;
		
		while ( running )
		{
			try
            {
	            ClusterEvent event = queue.take();
	            handleClusterEvent(event);
            }
            catch (InterruptedException e)
            {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            running = false;
            }
		}
	}
	
	private void handleClusterEvent(ClusterEvent event)
	{
		//System.out.println("Cluster event! ==> " + event);
		
		IClusterEvtHandler handler = sfsClusterHandlers.get(event.getEventName());
		
		if (handler != null)
		{
			try
			{
				handler.handleClusterEvent(event);
			}
			catch (Exception e) 
			{
				log.warning("Problems handling cluster event: " + event.getEventName());
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * This method adds a new handler for a cluster event
	 * 
	 * @param eventName		the name of the event (should be a unique string)
	 * @param handler		the handler
	 */
	public void addEventHandler(String eventName, IClusterEvtHandler handler)
	{
		sfsClusterHandlers.put(eventName, handler);
	}
}
