extends Node

@onready var effect_system: Node = get_node("../EffectSystem")

var _applied: Dictionary = {}

func _ready() -> void:
  EventBus.damage_requested.connect(_on_damage_requested)
  EventBus.entity_died.connect(_on_died)

func _on_damage_requested(attacker: Node, target: Node, _amount: float, element: int) -> void:
  if not multiplayer.is_server() and multiplayer.multiplayer_peer != null:
    return
  if element == Element.NONE:
    return
  if not is_instance_valid(target):
    return
  if not (target.is_in_group("enemies") or target.is_in_group("portals") or target.is_in_group("gates")):
    return
  apply_element(attacker, target, element)

func apply_element(source: Node, target: Node, element: int) -> void:
  if element == Element.NONE or not is_instance_valid(target):
    return
  _applied[target] = element
  EventBus.element_applied.emit(target, element)
  if element == Element.FIRE:
    var dot := Effect.new()
    dot.effect_name = &"fire_dot"
    dot.type = Effect.Type.DOT
    dot.value = 3.0
    dot.duration = 6.0
    dot.tick_interval = 2.0
    dot.element = Element.FIRE
    effect_system.apply(target, dot, source)

func _on_died(entity: Node) -> void:
  _applied.erase(entity)
