package sfs.cluster.lobby.handlers.cluster;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.User;
import it.gotoandplay.smartfoxserver.data.Zone;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Logger;

import org.json.JSONObject;

import sfs.cluster.lobby.ClusterLobbyExtension;
import sfs.cluster.lobby.data.ClusterEvent;

/**
 * This event is received when a private message was sent from a user from another server node
 */
public class OnPrivateMessage implements IClusterEvtHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	Zone zone;
	
	public OnPrivateMessage(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterLobbyExtension) parentExtension;
	    this.zone = SmartFoxServer.getInstance().getZone(parentExtension.getOwnerZone());
	    log = SmartFoxServer.log;
    }
	
	// Handle event
	public void handleClusterEvent(ClusterEvent event) throws Exception
	{
	    JSONObject jso = new JSONObject((HashMap) event.getParams().get("jso"));
	    String recipientName = (String) event.getParams().get("recipient");
	    
	    User localRecipient = zone.getUserByName(recipientName);
	    
	    if (localRecipient != null)
	    {
	    	LinkedList localRecipients = new LinkedList();
	    	localRecipients.add(localRecipient.getChannel());
	    	
	    	parentExtension.sendResponse(jso, -1, null, localRecipients);
	    }
	}
}
