extends Node2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer

@export var interactable_system: Node2D
## Amount of time the boss remains stunned if they're hit by the trap.
@export var stun_duration : float = 5
## Amount of damage e.g. the player takes if they're hit by the trap.
## This does not affect the boss (for now?).
@export var standard_damage : int = 1

var trap_active = false

var saved_state_active = false

@onready var trap_area: Area2D = $TrapArea

func _ready() -> void:
	animation_player.play("shadow_swinging")
	SignalBus.boss_reload_anchor.connect(reset)
	SignalBus.player_died.connect(reset)
	
	SignalBus.set_anchor.connect(save_cur_state)
	SignalBus.reload_anchor.connect(load_saved_state)
	

func _process(_delta: float) -> void:
	if interactable_system.is_system_active:
		if not trap_active:
			trap_active = true
			hit_in_trap()
	else:
		if trap_active:
			trap_active = false

func save_cur_state():
	saved_state_active = trap_active

func load_saved_state():
	print("loaded ", saved_state_active)
	if not saved_state_active:
		animation_player.play("shadow_swinging")

func reset():
	interactable_system._reset_cur_active_count()
	interactable_system.is_system_active = false
	Globals.interactable_states[get_path()] = false
	trap_active = false
	animation_player.play("shadow_swinging")

func hit_in_trap():
	animation_player.play("activate_trap")
	var bodies : Array[Node2D] = trap_area.get_overlapping_bodies()
	for body : Node2D in bodies:
		if body is Boss:
			body.stun(stun_duration)
			print("boss stunned")
		if body is GameAgent:
			body.take_damage(standard_damage)
		# boss trap tutorial
		if body is EnemyBase:
			print("eleeping enemy")
			for child in body.get_children():
				if child is StaticBody2D:
					var force_field = child
					if force_field:
						print("ff", force_field.name)
						force_field.visible = false
						force_field.collision_layer = 0
			
