extends Node

func _ready() -> void:
  _emit_initial.call_deferred()

func _process(delta: float) -> void:
  _regen_player(delta)
  _regen_entities(delta, EnemyData.entities)
  _regen_entities(delta, BossData.entities)

func _regen_player(delta: float) -> void:
  if not PlayerData.alive or PlayerData.health_regen <= 0:
    return
  if PlayerData.health < PlayerData.max_health:
    var health: float = min(PlayerData.health + PlayerData.health_regen * delta, PlayerData.max_health)
    PlayerData.set_health(health)

func _regen_entities(delta: float, entities: Dictionary) -> void:
  for entity in entities:
    if not is_instance_valid(entity):
      continue
    var data: Dictionary = entities[entity]
    if not data["alive"]:
      continue
    var regen: float = data["health_regen"]
    if regen > 0 and data["health"] < data["max_health"]:
      data["health"] = min(data["health"] + regen * delta, data["max_health"])
      EventBus.health_changed.emit(entity, data["health"], data["max_health"])

func _emit_initial() -> void:
  EventBus.health_changed.emit(PlayerData, PlayerData.health, PlayerData.max_health)
  EventBus.shield_changed.emit(PlayerData, PlayerData.shield, PlayerData.max_shield)
