package sfs3.extensions.examples.tictactoe.handlers;

import java.util.Map;

import com.smartfoxserver.core.ISFSEvent;
import com.smartfoxserver.core.SFSEventParam;
import com.smartfoxserver.core.SFSEventType;
import com.smartfoxserver.entities.Room;
import com.smartfoxserver.exceptions.SFSException;
import com.smartfoxserver.extensions.BaseServerEventHandler;

import sfs3.extensions.examples.tictactoe.TicTacToeExtension;

/**
 * This handler receives the signal that a user disconnected or left the game Room.
 */
public class OnUserGoneHandler extends BaseServerEventHandler
{
	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException
	{
		TicTacToeExtension gameExt = (TicTacToeExtension) getParentExtension();
		Room gameRoom = gameExt.getParentRoom();
		
		// Get id of the player who left the game
		// This can't be extracted from the User object available in event parameters, so we have to rely on other parameters 
		Integer oldPlayerId;
		
		// User disconnected
		if (event.getType() == SFSEventType.USER_DISCONNECT)
		{
			@SuppressWarnings("unchecked")
			Map<Room, Integer> playerIdsByRoom = (Map<Room, Integer>) event.getParameter(SFSEventParam.PLAYER_IDS_BY_ROOM);
			
			oldPlayerId = playerIdsByRoom.get(gameRoom);
		}
		
		// User left the room
		else
			oldPlayerId = (Integer) event.getParameter(SFSEventParam.PLAYER_ID);
		
		if (oldPlayerId != null)
		{
			// Check if gone user was a player
			if (oldPlayerId > 0)
			{
				// Stop game resetting turn and players wins
				gameExt.stopGame(true);
				
				// If a player is still inside the game room, notify them that the game is now stopped
				if (gameRoom.getSize().getUserCount() > 0)
					gameExt.send("stop", null, gameRoom.getUserList());
			}
		}
	}
}
