class_name InteractableSystem
extends Node2D

@export var part_of_bossfight : bool = false

var interactable_count
var cur_active_count = 0
var is_system_active = false

var nodepath : NodePath

signal state_changed(active : bool)

func _ready() -> void:
	# add to global dictionary or get state if already exists
	nodepath = get_path()
	if nodepath not in Globals.interactable_states:
		Globals.interactable_states[nodepath] = is_system_active
	if not part_of_bossfight:
		is_system_active = Globals.interactable_states[nodepath]
	
	interactable_count = get_child_count()  # gets amount of levers (children in the system)
	SignalBus.reload_anchor.connect(_reset_cur_active_count)  # s.t. active ones arent counted twice. all children should call notify_system again.

func _reset_cur_active_count():
	cur_active_count = 0   
	
func notify_system(active: bool):
	cur_active_count = 0
	for interactable in get_children():
		if interactable.active:
			cur_active_count += 1
	
	#print("new count", cur_active_count, " of ", interactable_count)
	
	# activate system if all levers are active
	if cur_active_count >= interactable_count:
		#print("FBI open up!!")
		is_system_active = true
		AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.INTERACTABLE_SYSTEM_ACTIVATED)
		# save globally
		Globals.interactable_states[nodepath] = is_system_active
	elif is_system_active:  # else close again if it is currently open/active
		is_system_active = false
		AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.INTERACTABLE_SYSTEM_ACTIVATED)
		# save globally
		Globals.interactable_states[nodepath] = is_system_active
	state_changed.emit(is_system_active)
	
