extends Node

enum Element { NONE, FIRE }

var applied_elements: Dictionary = {}

func _ready() -> void:
  EventBus.element_damage_dealt.connect(_on_element_damage_dealt)
  EventBus.entity_died.connect(_on_entity_died)
  EventBus.effect_expired.connect(_on_effect_expired)

func _on_element_damage_dealt(attacker: Node, target: Node, _amount: float, element: int) -> void:
  if element == Element.NONE:
    return
  if not target.is_in_group("enemies") and not target.is_in_group("portals"):
    return
  var current: int = applied_elements.get(target, Element.NONE)
  if current != Element.NONE and current != element:
    _trigger_reaction(attacker, target, current, element)
    return
  _apply_element(attacker, target, element)

func _apply_element(source: Node, target: Node, element: int) -> void:
  applied_elements[target] = element
  EventBus.element_applied.emit(target, element)
  match element:
    Element.FIRE:
      _apply_fire(source, target)

func _apply_fire(source: Node, target: Node) -> void:
  var fire_dot := Effect.new()
  fire_dot.effect_name = "Burning"
  fire_dot.type = Effect.Type.DEBUFF
  fire_dot.stat = "damage"
  fire_dot.value = 3.0
  fire_dot.duration = 6.0
  fire_dot.is_multiplier = false
  fire_dot.tick_interval = 2.0
  fire_dot.element = Element.FIRE
  EventBus.effect_requested.emit(target, fire_dot, source)

func _trigger_reaction(_attacker: Node, target: Node, _elem_a: int, _elem_b: int) -> void:
  applied_elements.erase(target)
  EventBus.element_reaction.emit(target, _elem_a, _elem_b, "")

func _on_entity_died(entity: Node) -> void:
  applied_elements.erase(entity)

func _on_effect_expired(target: Node, effect: Effect) -> void:
  if effect.element != Element.NONE:
    var current: int = applied_elements.get(target, Element.NONE)
    if current == effect.element:
      applied_elements.erase(target)
