extends Node

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

var bullet = preload("res://scenes/bullet.tscn")
@onready var gameController: Node3D = $".."

func _ready() -> void:
	gameController.destroy_signal.connect(destroy)
#factory decides to issue new bullet, or
#recycle an old one
func bulletFactory():
	var mybullet
	
	if bulletArray.size() < 4:
		mybullet = bullet.instantiate()
		mybullet.connect("hit", gameController.onBulletHit)
		owner.add_child(mybullet)
	else:
		mybullet = bulletArray.pop_back()
	mybullet.setSpeed(700)
	bulletArray.push_front(mybullet)
	bulletsMadeTotal +=1
	return mybullet

#order desk for new bullets
func makeBullet(position, speed):
	var myBullet = bulletFactory()
	myBullet.transform.origin = position
	myBullet.setSpeed(speed)
	return myBullet

func destroy(body):
	if body is Crate:
		body.queue_free()
	if body is Bullet:
		bulletArray.erase(body)
		body.queue_free()
