extends Node

func _ready() -> void:
  if multiplayer.multiplayer_peer != null and not multiplayer.is_server() and not (multiplayer.multiplayer_peer is OfflineMultiplayerPeer):
    set_physics_process(false)
  else:
    set_physics_process(true)

var _regen_accum: float = 0.0

func _physics_process(delta: float) -> void:
  if not multiplayer.is_server() and multiplayer.multiplayer_peer != null:
    return
  _regen_accum += delta
  if _regen_accum < 0.20:
    return
  var dt: float = _regen_accum
  _regen_accum = 0.0
  for entity in Stats.entities():
    if not is_instance_valid(entity):
      continue
    var hp: float = float(Stats.get_stat(entity, "health", 0.0))
    if hp <= 0.0:
      continue
    var max_shield: float = float(Stats.get_stat(entity, "max_shield", 0.0))
    if max_shield <= 0.0:
      continue
    var shield: float = float(Stats.get_stat(entity, "shield", 0.0))
    var timer: float = float(Stats.get_stat(entity, "shield_regen_timer", 0.0))
    if timer > 0.0:
      Stats.set_stat(entity, "shield_regen_timer", max(0.0, timer - dt))
      continue
    if shield < max_shield:
      var regen: float = float(Stats.get_stat(entity, "shield_regen", 0.0))
      if regen <= 0.0:
        regen = max_shield * 0.10
      var new_shield: float = min(max_shield, shield + regen * dt)
      Stats.set_stat(entity, "shield", new_shield)
      EventBus.shield_changed.emit(entity, new_shield, max_shield)
