extends Area3D

@export_file("*.tscn") var target_scene_path := "res://scenes/Levels/transportation_level.tscn"
@export var target_group: StringName = &"player"
@export var one_shot := true

var _is_transitioning := false


func _ready() -> void:
	body_entered.connect(_on_body_entered)


func _on_body_entered(body: Node) -> void:
	if _is_transitioning:
		return
	if target_group != StringName() and not body.is_in_group(target_group):
		return
	if target_scene_path.strip_edges() == "":
		push_warning("Teleporter target scene is empty.")
		return
	if not ResourceLoader.exists(target_scene_path):
		push_warning("Teleporter target scene does not exist: %s" % target_scene_path)
		return

	_is_transitioning = true
	if one_shot:
		set_deferred("monitoring", false)
	call_deferred("_deferred_change_scene")


func _deferred_change_scene() -> void:
	var err := get_tree().change_scene_to_file(target_scene_path)
	if err == OK:
		return
	push_warning("Failed to change scene to '%s' (%s)." % [target_scene_path, err])
	_is_transitioning = false
	if one_shot:
		set_deferred("monitoring", true)
