extends CharacterBody3D
class_name CharacterWrapper

@export var die_script: GDScript = null
@export var owner_placeholder: CharacterBody3D = null

@export var interpolation_speed: float = 50.0  # How quickly the model corrects position
@export var velocity_influence: float = 1.0  # How much velocity is used for smoothing

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	set_multiplayer_authority(multiplayer.get_unique_id())
	global_position = owner_placeholder.global_position
	
func _physics_process(delta: float) -> void:
	#if not is_on_floor():
		#velocity += get_gravity() * delta
	#global_position = owner_placeholder.global_position
		
	var server_pos = owner_placeholder.global_transform.origin
	var server_velocity = (server_pos - owner_placeholder.global_transform.origin) / delta
   
	velocity = owner_placeholder.velocity
	global_transform.origin = global_transform.origin.lerp(server_pos, interpolation_speed * delta)
	global_transform.origin += velocity * velocity_influence * delta
	velocity = velocity.lerp(server_velocity, delta * interpolation_speed)
	#move_and_slide()

# Set the owner placeholder, so the characters can send the requests to a node
# it depends on
func set_owner_placeholder(owner_placeholder: Node3D):
	owner_placeholder = owner_placeholder
	
func die():
	push_warning("TODO: Implement ragdoll kind of dying and respawn character as an object")
	queue_free()


func _on_area_body_part_hit(damage: int) -> void:
	# The owner node should be aware of how to take damage, so we need to
	# pass the value.
	if owner_placeholder:
		if owner_placeholder.has_method("take_damage"):
			owner_placeholder.take_damage(damage)
		else:
			push_warning("Node doesn't know how to take the damage")
