extends CharacterBody3D

const SPEED = 5.0
const JUMP_VELOCITY = 4.5

var synced_position := Vector3.ZERO
var synced_rotation := Vector3.ZERO

# Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

var has_control = false

func _ready():
	has_control = name == str(multiplayer.get_unique_id())
	print( 'I am ' + str(multiplayer.get_unique_id()))
	print( 'or ' + str(multiplayer.get_remote_sender_id()))
	has_control = !Globals.is_server
	if Globals.is_server == false && has_control:
		print ( 'Taking control!')
		get_node("Camera3D").current = true

func _physics_process(delta):
	if not has_control:
		position = synced_position
		rotation = synced_rotation
		return
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta

	# Handle Jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("strafe_left", "strafe_right", "move_forward", "move_backward")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)
	move_and_slide()
	
	if Input.is_action_pressed("look_left"):
		rotation.y += 0.02
	if Input.is_action_pressed("look_right"):
		rotation.y -= 0.02
	rpc_id(1, StringName('update_server'), position, rotation)
	#update_server(position, rotation).rpc()

@rpc("any_peer", "call_remote", "unreliable_ordered")
func update_server(pos: Vector3, rot: Vector3):
	if not multiplayer.is_server():
		return
	#if name != str(multiplayer.get_remote_sender_id()):
		##print ("foei?")
		#return
	synced_position = pos
	synced_rotation = rot
