# ---------------------------------------------------------------------
# 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
class_name PlayerInputController

var jumping: bool = false
var shooting: bool = false
var moving: bool = false
var look_dir: Vector2
var input_direction := Vector2()
var camera_sens: float = 0.002

const JUMP_VELOCITY = 4.5
var character_speed: int = 5

var controlled_node: PlayerPlaceholder = null
@export var owner_id: int = 0

@onready var camera_mount = $CameraMount
func _ready() -> void:
	set_multiplayer_authority(multiplayer.get_unique_id())
	global_position = controlled_node.global_position
	rotation = controlled_node.rotation

func _input(event):
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if Input.is_action_just_pressed("jump"): jump()
		if Input.is_action_just_released("shoot"): shooting = false
		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)
			controlled_node.set_rotation_x.rpc_id(1, rotation.x)
			controlled_node.set_rotation_y.rpc_id(1, rotation.y)
		if Input.is_action_pressed("move_left") or Input.is_action_pressed("move_right") or Input.is_action_pressed("move_forward") or Input.is_action_pressed("move_backwards"):
			moving = true
		else:
			moving = false

func jump():
	jumping = true
	controlled_node.jump.rpc_id(1)

func _physics_process(delta: float) -> void:	
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		input_direction = Input.get_vector("move_left", "move_right", "move_forward", "move_backward")
		controlled_node.set_input_direction.rpc_id(1, input_direction)
		if not is_on_floor():
			velocity += get_gravity() * delta
		if is_on_floor() && jumping:
			velocity.y = JUMP_VELOCITY
			
		#if shooting:
		jumping = false
		
		var direction := (transform.basis * Vector3(input_direction.x, 0, input_direction.y)).normalized()
		if is_on_floor():
			if direction:
				#first_view_legs_anim.play("Run Forward")
				velocity.x = direction.x * character_speed
				velocity.z = direction.z * character_speed
			else:
				velocity.x = move_toward(velocity.x, 0, character_speed)
				velocity.z = move_toward(velocity.z, 0, character_speed)
		#controlled_node.sync_velocity.rpc_id(1, velocity.x, velocity.y, velocity.z)
				

func _process(delta: float) -> void:
	move_and_slide()
