extends Node2D
class_name Bee

@onready var fsm : FiniteStateMachine = $StateMachine as FiniteStateMachine
@onready var drone_manager : DroneManager = get_tree().get_first_node_in_group("dronemanager") as DroneManager
@onready var bee_position_animation : AnimationPlayer = $BeePositionAnimation as AnimationPlayer
@onready var bee_wing_animation : AnimationPlayer = $WingAnimation as AnimationPlayer
@onready var bee_body : Sprite2D = $BeeBody as Sprite2D
@onready var impact_cloud : CPUParticles2D = $ImpactCloud

@export var nectar : int = 0
@export var speed : int = 30

var latest_target_director : int = 0

# This is updated when the bee enters or exits a flower patch 
var in_range_of_flowers : bool = false
var just_gathering : bool = false # Used to check if the bee has just been gathering to return to their previous director 

func _ready() -> void:
	modulate = Color(1,1,1,1)
	impact_cloud.visible = false
	speed = randi_range(35,55) # Randomise the bee speed a bit
	bee_wing_animation.play("Fly")

func get_current_director() -> DirectorDrone:
	return drone_manager.get_director(latest_target_director)

## Get the next target to move to
## If we have no nectar, we need to go up the director list 
## If we have nectar, we need to go down the director list 
## If we are at the lower director, we need to go the hive 
## If we are at the highest director, we need to go to a flower
func get_next_target() -> Drone:
	if nectar == 0:
		Log.pr("No nectar!")
		
		## If there is a next directory drone, lets go to it
		var next_drone : DirectorDrone = drone_manager.get_next_director(latest_target_director)
		if next_drone:
			latest_target_director = next_drone.visit_order
			return next_drone

		## If there is no next drone, check for a collector drone 
		var collector_drone : CollectorDrone = drone_manager.get_collector()
		if collector_drone:
			return collector_drone
	else:
		## Let's go home, we need the previous director drones location 
		var previous_drone : DirectorDrone = drone_manager.get_previous_director(latest_target_director)
		if previous_drone:
			Log.pr("Previous drone", previous_drone)
			latest_target_director = previous_drone.visit_order
			return previous_drone
		else:
			Log.pr("No previous drone")
			return null

	return null

func deposit_nectar() -> void:
	if nectar > 0:
		GameState.add_nectar(nectar)
		nectar = 0
		latest_target_director = 0
		just_gathering = false
	
func die() -> void:
	# Move to the death state 
	fsm.force_change_state("Death")





