extends Node

@onready var crates: Node2D = $"../crates"
@onready var triggers: Node2D = $"../triggers"
@onready var coins: Node2D = $"../coins"
@onready var badguys: Node2D = $"../badguys"
@onready var player: Player = $"../CharacterBody2D"
@onready var ui: Control = $"../CanvasLayer/ui"
@onready var audio_stream_player: AudioStreamPlayer = $AudioStreamPlayer

var bulletsFiredTotal = 0
var bulletsMadeTotal = 0
var bulletArray= []

var bullet = preload("res://scenes/bullet.tscn")

# bullet factory - makes bullets
func bulletFactory():
	var mybullet
	if bulletArray.size() < 7:
		#new bullet
		mybullet = bullet.instantiate()
		mybullet.connect("hit", bulletHit)
		owner.add_child(mybullet)
	else:
		#recycled bullet
		mybullet = bulletArray.pop_back()
		
	bulletArray.push_front(mybullet)
	return mybullet
	
# order desk for bullets
func makeBullet(position, speed):
	var newBullet = bulletFactory()
	
	newBullet.setSpeed(speed)
	newBullet.transform = position
	
func bulletHit(bullet, body):
	Gamecontroller.bulletHit(body)
	bullet.setSpeed(0)
	bullet.position = Vector2(-100,-100)
	
func destroy(body):
	body.queue_free()

func buildLevel():
	#how many crates?
	var totalCrates = 0
	for obj in crates.get_children():
		if obj is Crate:
			totalCrates +=1
	Gamecontroller.numberOfCrates(totalCrates)
	
	#how many coins?
	var totalCoins = 0
	if coins:
		for obj in coins.get_children():
			if obj is Coin:
				totalCoins +=1
				obj.coinCollectedSignal.connect(Gamecontroller.coinCollected)
		Gamecontroller.numberOfCoins(totalCoins)
	#how many badguys?
	var totalBadguys = 0
	if badguys:
		for obj in badguys.get_children():
			if obj is Slime:
				totalBadguys +=1
				obj.playerDamageSignal.connect(Gamecontroller.playerDamage)
				Gamecontroller.addEnemyToLevel(obj)
		Gamecontroller.numberOfBadguys(totalBadguys)
	#wire up the triggers
	for obj in triggers.get_children():
		if obj is Trigger:
			# wire up to GC
			obj.areaTrigger.connect(Gamecontroller._on_trigger_area_trigger)
	
	#listen to gamnecontroller
	Gamecontroller.destroySignal.connect(destroy)
	Gamecontroller.levelCompleteSignal.connect(loadLevel)
	Gamecontroller.playerHurtSignal.connect(playerHurt)
	Gamecontroller.playerHurtSignal.connect(ui.healthUpdate)
	Gamecontroller.playerKillSignal.connect(playerKill)
	Gamecontroller.timeCountSignal.connect(ui.timeUpdate)
	Gamecontroller.coinCountSignal.connect(ui.coinsUpdate)
	player.playerDeadSignal.connect(Gamecontroller.playerDeathComplete)
	
func loadLevel(level):
	get_tree().change_scene_to_file(level)
	
func _ready() -> void:
	buildLevel()
	Gamecontroller.reset()
	audio_stream_player.play
func playerHurt(health, _maxHealth):
	player.hurtPlayer(health)
func playerKill():
	player.killPlayer()
	
