package sfs3.extensions.examples.mmodemo.handlers;

import java.util.LinkedList;
import java.util.List;

import com.smartfoxserver.SmartFoxServer;
import com.smartfoxserver.annotations.Instantiation;
import com.smartfoxserver.api.ISFSMMOApi;
import com.smartfoxserver.bitswarm.data.TransportType;
import com.smartfoxserver.entities.User;
import com.smartfoxserver.entities.data.ISFSObject;
import com.smartfoxserver.entities.variables.SFSUserVariable;
import com.smartfoxserver.entities.variables.UserVariable;
import com.smartfoxserver.extensions.BaseClientRequestHandler;
import com.smartfoxserver.mmo.BaseMMOItem;
import com.smartfoxserver.mmo.IMMOItemVariable;
import com.smartfoxserver.mmo.MMOItemVariable;
import com.smartfoxserver.mmo.MMORoom;

import sfs3.extensions.examples.mmodemo.MMODemoExtension;

@Instantiation
public class ItemClickRequestHandler extends BaseClientRequestHandler
{
	private static final String MMOITEMVAR_OPEN = "open";
	private static final String USERVAR_ITEM_COUNT = "cnt";
	
	@Override
	public void handleClientRequest(User sender, ISFSObject params, TransportType transportType)
	{
		ISFSMMOApi mmoApi = SmartFoxServer.getInstance().getAPIManager().getMMOApi();
		
		MMORoom room = (MMORoom) this.getParentExtension().getParentRoom();
		
		// Retrieve the clicked MMOItem
		int itemId = params.getInt("id");
		BaseMMOItem item = room.getMMOItemById(itemId);
		
		if (item != null)
		{
			IMMOItemVariable var = item.getVariable(MMOITEMVAR_OPEN);
			
			if (!var.getBoolValue())
			{
				// Update item status (set it to "opened")
				List<IMMOItemVariable> iVariables = new LinkedList<IMMOItemVariable>();
				iVariables.add(new MMOItemVariable(MMOITEMVAR_OPEN, true));
				
				mmoApi.setMMOItemVariables(item, iVariables);
				
				// Spawn a new item on the map
				((MMODemoExtension) this.getParentExtension()).spawnMMOItem();
				
				// Update player counter of clicked items using a dedicated User Variable
				int counter = (sender.getVariable(USERVAR_ITEM_COUNT) != null ? sender.getVariable(USERVAR_ITEM_COUNT).getIntValue() : 0) + 1;
				
				List<UserVariable> uVariables = new LinkedList<UserVariable>();
				uVariables.add(new SFSUserVariable(USERVAR_ITEM_COUNT, counter));
				
				getParentExtension().getApi().setUserVariables(sender, uVariables);
			}
		}
	}
}
