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 fired when a friend list update should be sent to a certain user
 */
public class OnFriendListUpdate implements IClusterEvtHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	Zone zone;
	
	public OnFriendListUpdate(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterLobbyExtension) parentExtension;
	    this.zone = SmartFoxServer.getInstance().getZone(parentExtension.getOwnerZone());
	    log = SmartFoxServer.log;
    }
	
	/*
	 * Get the list of names, find the relative local users in this node
	 * and dispatch the update
	 */
	public void handleClusterEvent(ClusterEvent event) throws Exception
	{
		LinkedList<Object> recipients = (LinkedList<Object>) event.getParams().get("recipients");
		JSONObject jso = new JSONObject((HashMap) event.getParams().get("jso"));
	    
		LinkedList localRecipients = new LinkedList();
		
		// Cycle through all names and find the actual users
		for (Object o : recipients)
		{
			User u = zone.getUserByName((String) o);
			
			if (u != null)
				localRecipients.add(u.getChannel());
		}
		
		// Dispatch message to node-local users
		parentExtension.sendResponse(jso, -1, null, localRecipients);
	}
	
}
