package sfs.cluster.lobby.handlers.internal;

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.DataStore;
import sfs.cluster.lobby.data.ClusterEvent;
import sfs.cluster.lobby.data.ClusterUser;
import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.User;
import it.gotoandplay.smartfoxserver.events.InternalEventObject;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;
import it.gotoandplay.smartfoxserver.extensions.ExtensionHelper;

/**
 * Handles a local or cross-server Private Message
 */
public class PMHandler implements InternalHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	static final String TOKEN = new String(new byte[] {0x01});
	
	public PMHandler(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterLobbyExtension) parentExtension;
	    log = SmartFoxServer.log;
    }
	
	// Handle the event
	public void handleInternalEvent(InternalEventObject ieo) throws Exception
	{
	    String msg = ieo.getParam("msg");
	    User sender = (User) ieo.getObject("sender");
	    
	    /*
	     * Each message contains 2 parts, separated by a non printable character -> ASCII 0x01
	     * We split the string and obtain an array with two items:
	     * 
	     * 0 -> the name of the recipient
	     * 1 -> the actual chat message
	     */
	    String[] params = msg.split(TOKEN);
	    
	    User recipient = parentExtension.getCurrentZone().getUserByName(params[0]);
	    
	    // We use a custom JSON message for sending the PM
	    HashMap msgObj = new HashMap();
	    msgObj.put("_cmd", "pm");
	    msgObj.put("text", params[1]);
	    msgObj.put("sender", sender.getName());
	    
	    // send to local user
	    if (recipient != null)
	    {
	    	JSONObject jso = new JSONObject(msgObj);
	    	LinkedList localRecipients = new LinkedList();
	    	localRecipients.add(recipient.getChannel());
	    	
	    	parentExtension.sendResponse(jso, -1, null, localRecipients);
	    }
	    
	    // send to remote user
	    else
	    {
	    	ClusterUser remoteRecipient = parentExtension.getUserByName(params[0]);
	    	
	    	// Fire an event to the server where the recipient is connected
	    	if (remoteRecipient != null)
	    	{
		    	ClusterEvent event = new ClusterEvent(ClusterEvent.ON_PRIVATE_MESSAGE);
		    	event.getParams().put("jso", msgObj);
		    	event.getParams().put("recipient", params[0]);
		    	
		    	DataStore.instance().dispatchClusterEvent(event, remoteRecipient.getNodeId());
		   	}
	    }
	}
}
