package sfs2x.extensions.games.spacewar2.lobby.handlers.event;

import java.util.Arrays;
import java.util.Map;

import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.variables.SFSUserVariable;
import com.smartfoxserver.v2.entities.variables.UserVariable;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

import sfs2x.extensions.games.spacewar2.shared.util.Constants;

public class GameNodeEventHandler extends BaseServerEventHandler
{
	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException
	{
		@SuppressWarnings("unchecked")
		Map<String, Object> evtParams = (Map<String, Object>) event.getParameter(SFSEventParam.CLUSTER_EVENT_PARAMS);
		 
        String id = (String) evtParams.get("id");
 
        if (id.equals("gameover"))
        {
        	String userName = (String) evtParams.get("u");
        	int changeXp = (Integer) evtParams.get("xpc");
        	User user = getApi().getUserByName(userName);
			
        	// Calculate new user experience
			int currXp = user.getVariable(Constants.USERVAR_EXPERIENCE).getIntValue();
			int newXp = currXp + changeXp;
			
			if (newXp < 0)
				newXp = 0;
			else if (newXp > 5)
				newXp = Constants.SETTING_MAX_USER_XP;
			
			// Update user experience
			if (newXp != currXp)
			{
				UserVariable uv = new SFSUserVariable(Constants.USERVAR_EXPERIENCE, newXp);
				getApi().setUserVariables(user, Arrays.asList(new UserVariable[]{uv}));
			}
        }
	}
}