package sfs3.extensions.examples.shooter.handlers;

import com.smartfoxserver.bitswarm.data.TransportType;
import com.smartfoxserver.entities.Room;
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.shooter.simulation.Transform;
import sfs3.extensions.examples.shooter.simulation.World;
import sfs3.extensions.examples.shooter.utils.RoomHelper;
import sfs3.extensions.examples.shooter.utils.UserHelper;

import java.util.Date;
import java.util.List;

public class SendTransformHandler extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User u, ISFSObject data, TransportType txType)
	{
		// The transform we received from player
		Transform receivedTransform = Transform.fromSFSObject(data);
		World world = RoomHelper.getWorld(this);
		
		// Trying to apply new transform and return it or null if it's rejected
		Transform resultTransform = world.movePlayer(u, receivedTransform);
		
		if (resultTransform != null)
		{
			// Server accepted transform - send it to all the clients
			sendTransform(u, resultTransform);
		}
		else
		{
			// Server rejected transform - send corresponding message to client
			sendRejectedTransform(u);
		}
	}

	// Send the transform to all the clients
	private void sendTransform(User fromUser, Transform resultTransform)
	{
		SFSObject sfsObj = new SFSObject();
		
		// Adding server timestamp to transform here
		long time = (new Date()).getTime();
		resultTransform.setTimeStamp(time);
		resultTransform.toSFSObject((ISFSObject) sfsObj);
		sfsObj.putInt("id", fromUser.getId());
		
		Room currentRoom = RoomHelper.getCurrentRoom(this);
		List<User> userList = UserHelper.getRecipientsList(currentRoom);
		send("transform", (ISFSObject) sfsObj, userList, TransportType.UDP_UNRELIABLE); // Use UDP = true
	}

	// Sending rejected transform message to specified user
	private void sendRejectedTransform(User u)
	{
		SFSObject sfsObj = new SFSObject();
		RoomHelper.getWorld(this).getTransform(u).toSFSObject((ISFSObject) sfsObj);
		sfsObj.putInt("id", u.getId());
		send("notransform", (ISFSObject) sfsObj, u, TransportType.UDP_UNRELIABLE); // Use UDP = true
	}
}
