extends Area3D


@export var on_enter := {}
@export var on_exit := {}

var activated_on_start = false

@onready var timer = $Timer


signal activated(on_start)
signal deactivated
var first_time = true

func _process(delta: float) -> void:
	if first_time:
		#this is a bit ugly, but calls the signal activated with on_start true, when sonething is on it
		var layers = 32
		for mov in get_tree().get_nodes_in_group("movable"):
			for i in layers:
				if get_collision_mask_value(i+1) and mov.get_collision_layer_value(i+1):
					if abs((mov.position - position).length()) <= 1.9:
						print (str(mov.name) + " is closer <= 2")
						activated_on_start = true
						emit_signal("activated", true)
						first_time = false
					
	

func _ready() -> void:
	
	for o in on_enter:
		var node = get_node(o)
		if node != null and node.has_method(on_enter[o]):
			print ("node: " + str(node.name) + ", " + str(on_enter[o]))
			self.activated.connect(Callable(node, on_enter[o]))
		elif node != null:
			print (node.name)
	for o in on_exit:
		var node = get_node(o)
		if node != null and node.has_method(on_exit[o]):
			print ("node: " + str(node.name) + ", " + str(on_exit[o]))
			self.deactivated.connect(Callable(node, on_exit[o]))
			
	


func _on_ButtonTrigger_body_entered(body: Node3D) -> void:
	
	if timer.get_time_left() == 0:
		emit_signal("activated", false)


func _on_ButtonTrigger_body_exited(body: Node3D) -> void:
	if timer.get_time_left() == 0:
		if get_overlapping_bodies().size() == 0:
			emit_signal("deactivated")
		else:
			#else something exited and is still overlapping bodies
			if body.is_in_group("tool"):
				emit_signal("deactivated")
			


func _on_Timer_timeout() -> void:
	first_time = false
