extends CharacterBody3D
class_name Player

var input_dir := Vector2.ZERO
@onready var animation_tree: AnimationTree = $AnimationTree
@onready var pelvis: Node3D = $Node/base/pelvis
var not_dead := true

#@onready var weapon_slot_2: Area3D = $WeaponSlot2
#@onready var weapon_slot: Area3D = $WeaponSlot
@onready var collision_shape_3d: CollisionShape3D = $CollisionShape3D
#@onready var player_hit_box: Area3D = $PlayerHitBox
@onready var node: Node3D = $Node
#@onready var explosion: Node3D = $Explosion
#@onready var audio_stream_player: AudioStreamPlayer = $AudioStreamPlayer

@export_multiline var death_message : Array[String]
#@onready var color_rect: ColorRect = $CanvasLayer/ColorRect

func handle_dying():
	not_dead = false
	#weapon_slot_2.queue_free()
	#weapon_slot.queue_free()
	collision_shape_3d.queue_free()
	#player_hit_box.queue_free()
	node.queue_free()
	#explosion.play()
	#HudSignalBus.roll_dialog.emit(death_message)
	#audio_stream_player.play()
	#get_tree().create_tween().tween_property(color_rect, "color", Color.BLACK, 5)
	#get_tree().create_timer(5).timeout.connect(foo)

func handle_animations():
	if !not_dead:
		return
	animation_tree.set("parameters/walk_timescale/scale", (velocity.length())/3)
	
	if velocity.length() > 0.1:
		pelvis.look_at(global_position+velocity)
	pelvis.rotation.x = 0
	pelvis.rotation.z = 0
	
	if velocity.length() < 0.1 and animation_tree.get("parameters/idle_walk_blend/blend_amount") >= 1:
		var tween = get_tree().create_tween()
		tween.tween_property(animation_tree, "parameters/idle_walk_blend/blend_amount", 0, .5)
		#tween.connect("finished", $FootSoundPlayer.play)
	
	if (velocity.length()) > 0.1 and animation_tree.get("parameters/idle_walk_blend/blend_amount") == 0:
		var tween = get_tree().create_tween()
		tween.tween_property(animation_tree, "parameters/idle_walk_blend/blend_amount", 1, .5)

func _physics_process(delta: float) -> void:
	

	handle_animations()
	
	var asd = Vector2.ZERO
	if not_dead:
		#if Input.is_action_just_pressed("shoot3"):
			#handle_dying()
	
		asd = Input.get_vector("strafe_left", "strafe_right", "move_front", "move_back")*5
		rotation.y -= delta*Input.get_axis("turn_left","turn_right")*2
	
		input_dir = lerp(input_dir, asd, .1)	
		
		var input_velocity = Vector3(input_dir.x, 0, input_dir.y).rotated(Vector3.UP, rotation.y)
		velocity.x = input_velocity.x
		velocity.z = input_velocity.z
		velocity = velocity + Vector3.DOWN*1
		
		
		move_and_slide()
