extends Node

#This node is a scene manager. It is used to control all the visible
#assets in the viewport. However the scene manager does not encapsulate
#overall logic, and it does not persist data - that belongs to the GameManager,
#which is an autoload singleton.

var coinsCollected = 0

var crate = preload("res://scenes/crate.tscn")
@onready var boxtrap = $"../crates/boxtrap"
@onready var timer = $Timer
@onready var player = $"../CharacterBody2D"
@onready var ui = $"../UICanvas/UI"
@onready var crates = $"../crates"
@onready var coins = $"../coins"
@onready var enemies = $"../enemies"

func _ready():
	#Note: since autoloads persist, reset player to full health
	GameManager.resetPlayer()
	#Note: Add listeners to collectibles
	for n in coins.get_children():
		if n is Coin:
			n.coinCollected.connect(coinCollected)
	for n in enemies.get_children():
		if n is Enemy:
			n.playerDamage.connect(_on_badguy_player_damage)
	
func _on_area_2d_areatrigger(effect, body):
	match effect:
		"alert":
			#do stuff
			if body.is_in_group("player"):
				for n in 3:
					var box = crate.instantiate()
					owner.add_child(box)
					box.position = boxtrap.position
					
func coinCollected():
	print("scene manager saw coin collected")
	GameManager.coinsCollected +=1
	ui.coinsUpdate(GameManager.coinsCollected)

func resetGame():
	timer.start(.5)		
	
func _on_timer_timeout():
	get_tree().reload_current_scene()
	
#Scene control loop
func _process(delta):
	if GameManager.player.health < 0 && player.living:
		player.die()

func _on_badguy_player_damage():
	player.hurt()
	ui.healthUpdate(GameManager.player.health)
