extends CharacterBody3D
class_name Player

var _input: PlayerInputData = null

var input: PlayerInputData: 
	set(v):
		if _input != null:
			_input.drop.disconnect(drop)
			_input.claimed = false
		_input = v
		if _input != null:
			_input.drop.connect(drop)
			_input.claimed = true
	get:
		return _input

const SPEED = 5.0
const JUMP_VELOCITY = 4.5

enum initial {
	fox,
	vole,
}
@export var initial_model: initial

@onready var model = %vole if initial_model == initial.vole else %fox


func drop():
	_input = null

func _ready() -> void:
	%vole.visible = false
	%fox.visible = false
	model.visible = true
	if model == %vole:
		$VoleShape.visible = true
		$FoxShape.visible = false
	else:
		$VoleShape.visible = false
		$FoxShape.visible = true

func _physics_process(delta: float) -> void:
	if global_transform.origin.y < -100.0:
		queue_free()
	if not model.is_busy():
		if not is_on_floor():
			velocity.y = -10.0
		else:
			velocity.y = 0.0
	if input == null:
		return
	if not model.is_busy():
		var direction := input.walk_dir
		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)
		if direction.length() > 0.01:
			var target := global_transform.looking_at(global_position + input.walk_dir, Vector3(0.0, 1.0, 0.0)).basis.get_euler().y
			var current_euler := global_basis.get_euler()
			current_euler.y = lerp_angle(current_euler.y, target, delta * 20.0)
			global_basis = Basis.from_euler(current_euler)
			
			model.walk()
		else:
			model.idle()
		if input.jumping:
			model.pounce()
		
	position += model.global_transform.basis * model.root_motion()
	move_and_slide()