extends Area3D
class_name Health

@export var max_health: float = 5
var current_health: float

signal death

# Called when the node enters the scene tree for the first time.
func _ready():
	$SubViewport.set_update_mode(SubViewport.UPDATE_WHEN_PARENT_VISIBLE)
	current_health = max_health
	update_healthbar()


func set_maxhealth(value: float):
	max_health = value
	current_health = value
	update_healthbar()


func update_healthbar():
	var ratio = 100*current_health/max_health;
	$SubViewport/HealthBar/ProgressBar.value = ratio;
	if current_health == max_health:
		$SubViewport/HealthBar.visible = false;
	else:
		$SubViewport/HealthBar.visible = true;


func has_max_hp() -> bool:
	return current_health >= max_health


func add_health(added_hp: float):
	current_health = min(max_health, current_health + added_hp)
	update_healthbar()


func get_damage(area: DamageArea, damage: float):
	current_health = max(current_health - damage, 0.0)
	update_healthbar()
	if current_health <= 0:
		if not (get_parent() is Player):
			area.delete.emit()
		death.emit()


func _on_area_entered(area):
	var parent = get_parent()
	if area is DamageArea:
		get_damage(area, area.damage)
		if not (parent is Player):
			area.delete.emit()
		return
	if parent is Player and area is Item:
		area.on_pick_up(parent)
