extends Node2D

var score :int = 0
var level :int = 1
var current_level_root :Node = null

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	current_level_root = get_node("LevelRoot")
	_load_level(level)
	
func _load_level(level :int) -> void:
	if current_level_root:
		current_level_root.queue_free()
	var level_path = "res://level%s" % level +".tscn"
	current_level_root = load(level_path).instantiate()
	add_child(current_level_root)
	current_level_root.name = "LevelRoot"
	_setup_level(current_level_root)
	
	
func _setup_level(level_root :Node) -> void:
	var exit = level_root.get_node_or_null("Flag")
	if exit:
		exit.player_entered.connect(_on_exit_body_entered)
	
	var enemies = level_root.get_node_or_null("Enemies")
	if enemies:
		for enemy in enemies.get_children():
			enemy.player_died.connect(_on_player_dead)
	var apples = level_root.get_node_or_null("Apples")
	if apples:
		for apple in apples.get_children():
			apple.collected.connect(_increase_score)
			
func _on_player_dead(body):
	body._die()

func _increase_score() -> void:
	score += 1
	print(score)

func _on_exit_body_entered(body: Node2D):
	print(body)
	level += 1
	body.can_move = false
	_load_level(level)
