tool
extends Area2D

onready var anim_player: AnimationPlayer = $AnimationPlayer
onready var level_state := get_tree().root.get_child(4).get_node("%LevelState")
onready var signal_manager := get_tree().root.get_child(4).get_node("%SignalManager")
onready var levelName := get_tree().get_current_scene().get_name()

export(String, FILE, "*.tscn") var next_scene
export(bool) var is_active

func _ready() -> void:
	if(!is_active):
		monitoring = false
		signal_manager.connect("terminal_activated", self, "activate_portal")
	else:
		$portal.frame = 0

func _get_configuration_warning() -> String:
	return "The next scene property can't be empty" if not next_scene else ""

func level_completion() -> void:
	GlobalState.remove_savepoint(levelName)
	signal_manager.emit_signal("level_completed")

func activate_portal(_time: float) -> void:
	$AnimationPlayer.play("activatePortal")
	monitoring = true

func teleport() -> void:
	GlobalAudio.play_scene_independent("res://assets/sounds/MAGIC_SPELL_Morphing_Synth_Harp_Scales_stereo.wav", "Music", -15)
	get_tree().paused = true
	anim_player.play("fade_in")
	# TODO This doesn't pause the game but should
	yield(anim_player, "animation_finished")
	if ResourceLoader.exists(next_scene):
		get_tree().change_scene(next_scene)


func _on_body_entered(_body: Node) -> void:
	level_completion()
	teleport()
