package sfs.cluster.lobby.handlers.cluster;

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

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

import org.json.JSONArray;
import org.json.JSONObject;

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

/**
 * This event is fired when multiple users have been removed.
 * For example if a cluster node goes down.
 * A list of user names that were disconnected is sent to the clients in the remaining nodes.
 */
public class OnBatchUserRemove implements IClusterEvtHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	Zone zone;
	FriendListManager friendListManager;
	
	public OnBatchUserRemove(AbstractExtension parentExtension)
    {
		this.parentExtension = (ClusterLobbyExtension) parentExtension;	
	    this.zone = SmartFoxServer.getInstance().getZone(parentExtension.getOwnerZone());
	    log = SmartFoxServer.log;
	    
	    friendListManager = this.parentExtension.getFriendListManager();
    }
	
	// Handle event
	public void handleClusterEvent(ClusterEvent event) throws Exception
	{
		// Get the list of removed users
		List<String> removedUsers = (List<String>) event.getParams().get("userList");
		
		// Get the local batch-updates to execute
		List<Object[]> localClientsToUpdate = friendListManager.getLocalClientsForBatchRemoveUpdate(removedUsers);
		
		// for each item in the list send a message
		for (Object[] update : localClientsToUpdate)
		{
			JSONObject jso = new JSONObject();
			jso.put("_cmd", "fListBatchUpd");
			jso.put("list", (JSONArray) update[1]);
			
			this.parentExtension.sendResponse(jso, -1, null, (LinkedList) update[0]);
		}	
	}
}
