extends Area2D
class_name PlayerSpawnZone

@onready var shape: CollisionShape2D = $CollisionShape2D
@onready var markers: Node2D = $Markers

const DEMON_SCENE: PackedScene = preload("res://assets/scenes/demon.tscn")

func add_survivor() -> void:
	var demon_count = get_tree().get_nodes_in_group("survivor").size()
	if demon_count >= 9:
		return
	
	var spot = find_first_free_spot()
	if spot == null:
		return
	
	var demon = DEMON_SCENE.instantiate()
	demon.name = "Demon #%d" % (demon_count + 1)
	spot.add_child(demon)

func find_first_free_spot() -> Node2D:
	for marker in markers.get_children():
		if marker.get_child_count() == 0:
			return marker
	return null

func is_occupied() -> bool:
	return find_first_free_spot() == null

func drop(object: Node2D) -> void:
	object.reparent(find_first_free_spot())

func _on_mouse_entered() -> void:
	var da = GlobalInput.dragged_object
	if da == null:
		return
	
	var object_is_survivor = da.is_in_group("survivor")
	var spot_is_free = not is_occupied()
	var spot_is_not_source = not is_ancestor_of(da)
	
	if object_is_survivor && spot_is_free && spot_is_not_source:
		GlobalInput.set_drop_spot(self)

func _on_mouse_exited() -> void:
	if GlobalInput.drop_spot == self:
		GlobalInput.set_drop_spot(null)
