# ---------------------------------------------------------------------
# ---------------------------------------------------------------------
# This script is supposed to control the node that is rendered on the 
# client side, and send the changes to the server node
# ---------------------------------------------------------------------

extends CharacterBody3D

@export var jumping := false 
@export var input_direction := Vector2()

@onready var camera_mount = $CameraMount
@onready var camera = $CameraMount/Camera3D
@onready var placeholder: Node3D = $'..'
var paused := false

#func _ready() -> void:

var look_dir: Vector2
func _ready() -> void:
	global_position = $"..".initial_position
func _input(event):
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if event is InputEventMouseMotion and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			look_dir = event.relative * 1
			rotation.y -= look_dir.x * camera_sens * 1.0
			camera_mount.rotation.x = clamp(camera_mount.rotation.x - look_dir.y * camera_sens * 1.0, -1.5, 1.5)
			server_node.set_rotation_y.rpc_id(1, rotation.y)
			server_node.set_rotation_x.rpc_id(1, rotation.x)

@onready var server_node: ServerControlledPlayer = $"../ServerControlledNode"
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if !paused:
			Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		server_node.set_input_direction.rpc_id(1, input_direction)
		input_direction = Input.get_vector("move_left", "move_right", "move_forward", "move_backwards")
		if Input.is_action_just_pressed("jump"):
			jump.rpc_id(1)

func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity += get_gravity() * delta

	if multiplayer.get_unique_id() == get_multiplayer_authority():
		var direction := (transform.basis * Vector3(input_direction.x, 0, input_direction.y)).normalized()
		if is_on_floor():
			if direction:
				velocity.x = direction.x * placeholder.character_speed
				velocity.z = direction.z * placeholder.character_speed
			else:
				velocity.x = move_toward(velocity.x, 0, placeholder.character_speed)
				velocity.z = move_toward(velocity.z, 0, placeholder.character_speed)
		move_and_slide()

var camera_sens: float = 0.002

@rpc("authority", "reliable")
func set_current_rotation(rotation: Vector3):
	rotation = rotation

@rpc("any_peer", "reliable")
func set_current_position(x: float, y: float, z: float):
	global_position = Vector3(x, y ,z)

@rpc("any_peer", "call_local", "reliable")
func jump():
	jumping = true