extends Node

var MainInstances = ResourceLoader.MainInstances

onready var currentLevel = $Level_00

func _ready():
	VisualServer.set_default_clear_color(Color.black)
	
	if SaverLoader.is_loading:
		SaverLoader.load_game()
		SaverLoader.is_loading = false

	MainInstances.Player.connect("hit_door", self, "_on_Player_hit_door")
	
func _on_Player_hit_door(door):
	# Executes the function after the current tick of the game is done, to make
	# sure everything is ready to be switched since we're doing calculations
	# based on the current level
	call_deferred("change_levels", door)
	
func change_levels(door):
	var offset = currentLevel.position
	currentLevel.queue_free()
	var NewLevel = load(door.new_level_path)
	var newLevel = NewLevel.instance()
	add_child(newLevel)
	var newDoor = get_door_with_connection(door)
	var exit_position = newDoor.position - offset
	newLevel.position = door.position - exit_position
	
func get_door_with_connection(outgoingDoor):
	var doors = get_tree().get_nodes_in_group("Door")
	for door in doors:
		if door.connection == outgoingDoor.connection and door != outgoingDoor:
			return door
			
	return null
