package sfs3.extensions.examples.tictactoe.handlers;

import com.smartfoxserver.bitswarm.data.TransportType;
import com.smartfoxserver.entities.User;
import com.smartfoxserver.entities.data.ISFSObject;
import com.smartfoxserver.entities.data.SFSObject;
import com.smartfoxserver.extensions.BaseClientRequestHandler;

import sfs3.extensions.examples.tictactoe.TicTacToeExtension;

/**
 * This handler receives the "ready" notification from clients entering the Room.
 */
public class ReadyHandler extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User user, ISFSObject params, TransportType type)
	{
		TicTacToeExtension gameExt = (TicTacToeExtension) getParentExtension();
		
		if (user.isPlayer())
		{
			// Check if two players are available and start game
			if (gameExt.getParentRoom().getSize().getUserCount() == 2)
				gameExt.startGame();
		}
		else
		{
			// Send game board state to spectator
			ISFSObject outParams = new SFSObject();
			outParams.putInt("t", gameExt.getWhoseTurn() == null ? 0 : gameExt.getWhoseTurn().getPlayerId());
			outParams.putBool("run", gameExt.isGameStarted());
			outParams.putSFSArray("board", gameExt.getGameBoard().toSFSArray());
			outParams.putInt("p1w", gameExt.getPlayerWins(1));
			outParams.putInt("p2w", gameExt.getPlayerWins(2));
			
			// If the game ended right before the spectator joined, also send its outcome
			if (!gameExt.isGameStarted() && gameExt.getParentRoom().getSize().getUserCount() == 2)
				outParams.putInt("w", gameExt.getLastWinnerId());
			
			send("state", outParams, user);
		}
	}
}
