class_name ActivitySite
extends Node3D

static var _all: Array = []

@export var site_id: StringName
@export var action_id: StringName = SimulationIds.ACTION_REST
@export var display_name := "Activity Site"
@export_range(1, 12, 1) var capacity := 1
@export var debug_label_enabled := true

@onready var interaction_point: Marker3D = $InteractionPoint

var _last_label_text := ""


func _ready() -> void:
	if site_id.is_empty():
		push_error("ActivitySite at %s has empty site_id" % get_path())
		_update_presentation()
		return
	var existing: ActivitySite = get_by_id(site_id) as ActivitySite
	if existing != null:
		push_error(
			(
				"Duplicate ActivitySite site_id '%s' at %s; first registered at %s"
				% [site_id, get_path(), existing.get_path()]
			)
		)
		_update_presentation()
		return
	_all.append(self)
	add_to_group("activity_sites")
	_update_presentation()


func _process(_delta: float) -> void:
	if debug_label_enabled:
		_update_presentation()


func _exit_tree() -> void:
	_all.erase(self)


func get_interaction_position() -> Vector3:
	return interaction_point.global_position if interaction_point != null else global_position


func supports_action(candidate_action_id: StringName) -> bool:
	return action_id == candidate_action_id


func _update_presentation() -> void:
	if not has_node("DebugLabel"):
		return
	var label := $DebugLabel as Label3D
	label.visible = debug_label_enabled
	if not debug_label_enabled:
		return
	var text := "%s\n%s\ncap:%d" % [display_name, action_id, capacity]
	if text == _last_label_text:
		return
	_last_label_text = text
	label.text = text


static func get_by_id(search_id: StringName):
	for node in _all:
		if node.site_id == search_id:
			return node
	return null


static func get_all() -> Array:
	return _all.duplicate()
