class_name EnemyBase
extends GameAgent

@onready var enemy_behavior : BaseEnemyBehavior
@onready var enemy_avoidance: Node2D = $EnemyAvoidance

@export var walk_speed : float = 80
@export var chase_speed : float = 120

signal attack_over

var anchor_state : Dictionary = {}

var parent : Node
var anchor_active : bool = false
var perished : bool = false

func _ready() -> void:
	super._ready()
	parent = get_parent()
	enemy_behavior.died.connect(die)
	var levelgroups = get_groups().filter(func(group : String): return group.begins_with("Level"))
	if not levelgroups.is_empty():
		enemy_behavior.is_part_of_group = true
		enemy_behavior.room_enemy_group = levelgroups[0]
	SignalBus.alerted_enemies.connect(check_alert)
	SignalBus.set_anchor.connect(save_state)
	SignalBus.reload_anchor.connect(reload_state)
	SignalBus.anchor_ran_out.connect(anchor_ran_out)

func _process(_delta: float) -> void:
	$helper_arrow.rotation = atan2(current_direction.x, -current_direction.y)
	enemy_avoidance.rotation = atan2(current_direction.x, -current_direction.y)

func attack():  # TODO for cleaner code: could be called from super(). only attack_over.emit() is additional
	if weapon: return
	weapon = sword.instantiate()
	add_child(weapon)
	weapon.start(current_direction, attack_damage)
	AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.SWORD_SWING)
	
	await weapon.animation_player.animation_finished
	weapon.queue_free()
	weapon = null
	attack_over.emit()

func take_damage(damage : int):
	enemy_behavior.take_damage(damage)

func walk(direction : Vector2):
	move_with_speed(direction, walk_speed)

func chase(direction : Vector2):
	move_with_speed(direction, chase_speed)

func die():
	if anchor_active and parent:
		parent.remove_child(self)
		perished = true
	else:
		queue_free()

func check_alert(player_position : Vector2, enemy_group : String):
	if is_in_group(enemy_group):
		enemy_behavior.get_alerted(player_position)

func avoid_enemy():
	enemy_behavior.state_chart.send_event("avoid")

#region Anchored Remnant
func save_state():
	anchor_active = true
	anchor_state = {
		"global_position" = global_position,
		"current_direction" = current_direction,
	}
	enemy_behavior.save_state()

func reload_state():
	if perished and parent:
		parent.add_child(self)
		perished = false
		if enemy_behavior.set_anchor_during_death:
			enemy_behavior._on_die_state_entered()
	global_position = anchor_state.get("global_position", global_position)
	current_direction = anchor_state.get("current_direction", current_direction)
	enemy_behavior.reload_state()

func anchor_ran_out():
	anchor_active = false
	if perished:
		queue_free()
#endregion
