extends Node
class_name BunnyGenerator

@export var bunny_prefab : Resource
@export var player : CharacterBody2D
@export var player_save_distance : float = 400
@onready var BunnyPrefab : PackedScene = load(bunny_prefab.resource_path)

func spawn_bunny(pos : Vector2, team : int, health : int) -> Bunny:
	var bunny = BunnyPrefab.instantiate()
	self.add_child(bunny)
	bunny.global_position = pos
	bunny.health = health
	bunny.team = team
	bunny.player = player
	return bunny

func spawn_wave(free_tiles : Array, team: int, amount : int, health : int) -> Array:
	var bunnys = []
	
	# Make Sure that no possitions to near to the player are insdie of the list
	free_tiles = free_tiles.filter(func(val): return val.distance_to(player.global_position) > player_save_distance)
	# Make sure amount isnt bigger then available positions 
	if free_tiles.size() < amount: amount = free_tiles.size()
	
	# Spawn at random positions of the list
	for i in amount:
		var pos = free_tiles.pick_random()
		free_tiles.erase(pos)
		var bunny = spawn_bunny(pos, team, health)
		bunnys.push_back(bunny)
	return bunnys
	
func spawn_batched_wave(batch_size : float, batch_delay: float, free_tiles : Array, team: int, amount : int, health : int) -> Array:
	var bunnys = []
	var batch_count = ceil(amount / batch_size)
	var actual_batch_size = floor(amount / batch_count)
	var last_batch_size = amount - batch_size * batch_count
	
	for s in batch_count:
		bunnys += spawn_wave(free_tiles.duplicate(), team, actual_batch_size, health)
		await get_tree().create_timer(batch_delay).timeout
	bunnys += spawn_wave(free_tiles.duplicate(), team, last_batch_size, health)
	await get_tree().create_timer(batch_delay).timeout
	return bunnys
