extends CharacterBody3D
class_name Player

@export var jump_velocity: float = 4.5
@export var speed: float = 5.0

var dash_speed = speed * 5;
var is_dashing = false;

var is_dead: bool = false;
signal player_died


var weapon: Weapon
var stamina: Stamina
var health: Health

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")


func _ready():
	weapon = $MeshInstance3D/gun
	stamina = $Stamina
	health = $Health

func _physics_process(delta):
	if is_dead:
		return
	
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	
	if Input.is_action_pressed("fire"):
		weapon.attack()

	player_movement()
	move_and_slide()


func player_movement():
	var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	
	if Input.is_action_pressed("dash") and not is_dashing and stamina.can_use_stamina(60):
		stamina.change_stamina(-60)
		is_dashing = true;
		$DashTimer.start()
	
	var current_speed;
	if is_dashing:
		current_speed = dash_speed;
	else:
		current_speed = speed;
	
	if direction:
		velocity.x = direction.x * current_speed
		velocity.z = direction.z * current_speed
	else:
		velocity.x = move_toward(velocity.x, 0, current_speed)
		velocity.z = move_toward(velocity.z, 0, current_speed)


func _on_health_death():
	is_dead = true;
	player_died.emit()


func _on_dash_timer_timeout():
	is_dashing = false;


func _on_hud_upgrade_signal(upgrade_type):
	if upgrade_type == 'damage_up':
		weapon.damage += 0.5
	elif upgrade_type == 'fire_rate_up':
		weapon.attack_rate *= 0.85
	elif upgrade_type == 'max_health_up':
		health.max_health += 2.0
		health.add_health(2.0)
	elif upgrade_type == 'heal':
		health.add_health(health.max_health)
	elif upgrade_type == 'movement_speed_up':
		speed *= 1.2
	else:
		stamina.max_stamina *= 1.35
		stamina.recharge_speed *= 1.2
