class_name BossAccessDoor
extends StaticBody2D

@onready var sprite_2d: Sprite2D = $Sprite2D
var _closed_state: int  # for dis-/enabling collisions, if door open/closed

var _corresponding_door_in_present: BossAccessDoor
var own_id: int = 0

func _ready() -> void:
	_closed_state = collision_layer  # this line should be at the TOP of _ready 
	
	system_state_changed(Globals.boss_accessible)
	SignalBus.boss_accessible.connect(system_state_changed)
	# allowing multiple doors in 1 scene . rn up to 3
	if is_in_group("ActivatableDoor1"):
		own_id = 1
	elif is_in_group("ActivatableDoor2"):
		own_id = 2
	elif is_in_group("ActivatableDoor3"):
		own_id = 3
		
	# connect corresponding doors in past and present
	_connect_past_and_present_doors()

func system_state_changed(active : bool):
	if active:
		collision_layer = 0
		self.visible = false
		sprite_2d.hide()
		if _corresponding_door_in_present:
			_corresponding_door_in_present.system_state_changed(active)
	else:
		collision_layer = _closed_state
		self.visible = true
		sprite_2d.show()
		if _corresponding_door_in_present:
			_corresponding_door_in_present.system_state_changed(active)

func _connect_past_and_present_doors():
	if not is_inside_tree():
		return
	var found_doors_in_present = get_tree().get_nodes_in_group("CorrespondingActivatableDoorInPresent")
	for door in found_doors_in_present:
		if door == self:
			return
		if door.own_id == own_id:
			#print("same id!!", door.name, name)
			_corresponding_door_in_present = door
	#print("connected ", _corresponding_door_in_present, name)
