package sfs.cluster.lobby.handlers.client;

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

import org.json.JSONObject;

import sfs.cluster.lobby.ClusterLobbyExtension;
import sfs.cluster.lobby.friendlist.Friend;
import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.User;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

/**
 * Handles the addition of a Friend entry in a user's Friend List
 */
public class AddFriendHandler implements IClientRequestHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	
	public AddFriendHandler(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterLobbyExtension) parentExtension;
	    log = SmartFoxServer.log;
	}
	
	// Handle the event
	public void handleRequest(Object req, User sender, int roomId) throws Exception
	{
	    JSONObject jso = (JSONObject) req;
	    
	    String friendName = jso.getString("friend");
	    
	    // create friend object
	    Friend mate = new Friend(friendName, parentExtension.getNodeId());
	    
	    // add it to the clustered friend list
	    parentExtension.getFriendListManager().addFriend(sender.getName(), mate);
	    
	    log.info("Friend: " + friendName +" was added to " + sender.getName() + " friend-list.");
	    
	    // Prepare a user response, in json format
	    JSONObject response = new JSONObject();
	    response.put("_cmd", "addFriend");
	    response.put("friend", friendName);
	    response.put("status", parentExtension.isUserOnline(friendName) ? "1" : "0");
	    
	    // Send the response
	    LinkedList<Object> recipients = new LinkedList<Object>();
	    recipients.add(sender.getChannel());
	    
	    parentExtension.sendResponse(response, -1, null, recipients);
	}
}
