"""
	Asset: Godot Simple Portal System
	File: simple_portal_teleport.gd
	Description: An area which teleports a node through the parent node's portal.
	Instructions: For detailed documentation, see the README or visit: https://github.com/Donitzo/godot-simple-portal-system
	Repository: https://github.com/Donitzo/godot-simple-portal-system
	License: CC0 License
"""

extends Area3D
class_name SimplePortalTeleport

var _parent_portal: Portal

func _ready():
	_parent_portal = get_parent() as Portal
	if _parent_portal == null:
		push_error("The PortalTeleport \"%s\" is not a child of a Portal instance" % name)

	area_entered.connect(_on_area_entered)
	body_entered.connect(_on_body_entered)

func _on_area_entered(area: Area3D) -> void:
	if area.has_meta("teleportable_root"):
		var root:Node3D = area.get_node(area.get_meta("teleportable_root"))
		print("[%f] Teleporting %s to %s" % [roundi(Time.get_ticks_msec() / 100) / 10.0, root.name, _parent_portal.exit_portal.name])
		root.global_transform = _parent_portal.real_to_exit_transform(root.global_transform)

func _on_body_entered(body: Node3D) -> void:
	if body.get_meta("teleportable", false) == true:
		body.global_transform = _parent_portal.real_to_exit_transform(body.global_transform)
		print("Teleporting %s to %s" % [body.name, _parent_portal.exit_portal.name])
