package sfs2x.extensions.games.tictactoe.handlers;

import java.util.Map;

import sfs2x.extensions.games.tictactoe.TicTacToeExtension;

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

/**
 * 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());
			}
		}
	}
}
