extends Node

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

func _ready():
	GameManager.resetPlayer()
	ui.coinsUpdate(GameManager.coinCollectedTotal)
	ui.healthUpdate(GameManager.player.health)
	
	for n in coins.get_children():
		if n is Coin:
			n.coinCollected.connect(_on_area_2d_3_coin_collected)	
	for n in enemies.get_children():
		if n is badguy:
			n.playerDamage.connect(_on_badguy_player_damage)

func _process(delta):
	if GameManager.player.health <= 0 and player.living:
		player.die()


func _on_area_2d_areatrigger(effect, body):
	print("Game Controller sees the trigger "+effect)
	match effect:
		"alert":
			#do stuff
			print("hi")
			if body.is_in_group("player"):
				for n in 3:
					var box = crate.instantiate()
					owner.add_child(box)
					box.position = boxtrap.position
		"powerup":
			print("you got power")


	
func resetWorld():
	get_tree().reload_current_scene()


func _on_area_2d_3_coin_collected():
	print("SceneManager sees new coin")
	GameManager.coinCollected()
	ui.coinsUpdate(GameManager.coinCollectedTotal)


func _on_badguy_player_damage():
	print("run into bad guy")
	GameManager.playerDamage()
	ui.healthUpdate(GameManager.player.health)


func _on_death_complete():
	#This is where we reset the world
	timer.start(0.5)
