extends Node3D

@export var NumberOfClowns : int = 5
@export var TimeBetweenClowns : int = 2

@onready var spawn_position: Node3D = $SpawnPosition

var clown = preload("res://mechanics/clown/clown.tscn")

var spawnTimer : float = 0;

func _ready():
	self.position.z = -1.5
	
	# Add delay so car door can open
	spawnTimer = 1
	const ANIMATION_NAME: String = "Key_001Action_001"
	($ClownCar2/AnimationPlayer as AnimationPlayer).play(ANIMATION_NAME)

func _process(delta):
	spawnTimer-=delta
	if spawnTimer<0 && NumberOfClowns > 0:
		spawnTimer = TimeBetweenClowns
		NumberOfClowns -= 1
		var instance = clown.instantiate()
		get_parent().add_child(instance)
		instance.global_position = spawn_position.global_position
		instance.global_position.z = 0
		instance.crawl()
		
		if NumberOfClowns <= 0:
			finished()
		
		
func finished():
	await get_tree().create_timer(1.8).timeout
	const ANIMATION_NAME: String = "Key_001Action_001"
	($ClownCar2/AnimationPlayer as AnimationPlayer).play_backwards(ANIMATION_NAME)
	
