class_name ActivatableDoor
extends StaticBody2D

@export var interactable_system: InteractableSystem  # can be empty if e.g. it is the door in the present only openable through the systems in the past
@export var emergency_opener_system: InteractableSystem
@onready var sprite_2d: Sprite2D = $Sprite2D
var _closed_state: int  # for dis-/enabling collisions, if door open/closed

var _corresponding_door_in_present: ActivatableDoor
var own_id: int = 0

func _ready() -> void:
	_closed_state = collision_layer  # this line should be at the TOP of _ready 
	
	if not interactable_system:
		print("no interactable system assigned. ", name)
	
	# 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 _process(_delta: float) -> void:
	if not interactable_system:
		return
	system_state_changed(interactable_system.is_system_active)  
	# little bit overkill to do it in process, but it works
	

func system_state_changed(active):
	if active or (emergency_opener_system and emergency_opener_system.is_system_active):
		collision_layer = 0
		sprite_2d.visible = false
		if _corresponding_door_in_present:
			_corresponding_door_in_present.system_state_changed(active)
	else:
		collision_layer = _closed_state
		sprite_2d.visible = true
		if _corresponding_door_in_present:
			_corresponding_door_in_present.system_state_changed(active)
	# TODO idk right off the bat how to disable colliders s.t. it doesnt bug with the player, e.g. when they stand inside the door.
	

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)
