extends Node2D

@export var leaf_texture: Texture2D
@export var spawn_markers: Node2D
@export var destination_markers: Node2D

# Debug
@export var should_log_schedule := false

@export_range(0.0, 60.0) var minimum_schedule_gap := 20.0
@export_range(1.0, 61.0) var maximum_schedule_gap := 60.0

var _spawn_markers: Array[Marker2D] = []
var _destination_markers: Array[Marker2D] = []
var _spawn_schedule := 0.0
var _spawn_timer := 0.0

# Private Methods
func _ready() -> void:
	for child in spawn_markers.get_children():
		_spawn_markers.append(child)
	
	for child in destination_markers.get_children():
		_destination_markers.append(child)
	
	_set_random_spawn_schedule()
	
	# At spawn, we might want to spawn some leaves sooner...
	_spawn_schedule -= randf_range(0.0, _spawn_schedule)
	_spawn_schedule = max(0, _spawn_schedule)
	
	_log_schedule()


func _process(delta: float) -> void:
	_spawn_timer += delta
	if _spawn_timer >= _spawn_schedule:
		_spawn_timer = 0.0
		_set_random_spawn_schedule()
		_log_schedule()
		
		var spawn := _get_random_spawn_point()
		var destination := _get_random_destination_point()
		
		# TODO Refactor this into scene
		var sprite := Sprite2D.new()
		sprite.texture = leaf_texture
		sprite.position = spawn
		sprite.rotate(deg_to_rad(randf_range(0, 360)))
		var tween := get_tree().create_tween().tween_property(sprite, "position", destination, randf_range(2.0, 3.0))
		tween.finished.connect(
			func():
				var timer := get_tree().create_timer(randf_range(8.0, 15.0))
				timer.timeout.connect(
					func():
						if !sprite: return
						var tween2 := get_tree().create_tween().tween_property(sprite, "self_modulate:a", 0.0, randf_range(4.0, 6.0))
						tween2.finished.connect(
							func():
								if !sprite: return
								sprite.queue_free()
						)
				)
		)
		add_child(sprite)


func _set_random_spawn_schedule() -> void:
	_spawn_schedule = randf_range(minimum_schedule_gap, maximum_schedule_gap)


func _get_random_spawn_point() -> Vector2:
	var idx := randi_range(0, len(_spawn_markers) - 1)
	var marker := _spawn_markers[idx]
	return marker.position


func _get_random_destination_point() -> Vector2:
	var idx := randi_range(0, len(_destination_markers) - 1)
	var marker := _destination_markers[idx]
	var offset := Vector2(randf_range(-5.0, 5.0), randf_range(-5.0, 5.0))
	
	return marker.position + offset


func _log_schedule() -> void:
	if should_log_schedule:
		print("%s - Leaf Spawn Schedule: %f" % [get_parent().name, _spawn_schedule])
