extends CharacterBody2D
class_name Snail

@onready var fsm : FiniteStateMachine = $StateMachine as FiniteStateMachine
@onready var flowers : Flowers = get_parent()
@onready var sprite : Sprite2D = $Sprite

var enabled : bool = false
var eating : bool = false
var speed : float = 20.0
var mouse_over : bool = false

func _ready() -> void:
	connect("mouse_entered", Callable(self, "on_mouse_entered"))
	connect("mouse_exited", Callable(self, "on_mouse_exited"))

# Detect mouse left click and trigger function 
func _input(event : InputEvent) -> void:
	if mouse_over and eating:
		if event is InputEventMouseButton:
			if (event is InputEventMouseButton && event.button_index == MOUSE_BUTTON_LEFT && event.pressed):
				maybe_sleep()

func eat() -> void:
	# Play the munch animation and noise 

	# Reduce the GameState flower_nectar_level
	GameState.flower_nectar_level -= 1

func maybe_sleep() -> void:
	# If the snail is still eating, then we want a 30% chance of switching it it to the sleeping state
	if eating:
		if randf() < 0.3:
			if fsm.get_current_state_name() == "eating":
				fsm.change_state(fsm.current_state, "sleeping")

func get_random_target() -> Vector2:
	return flowers.get_random_circumference_points()

func on_mouse_entered() -> void:
	if eating:
		mouse_over = true
		CursorMgr.hand()
		Log.pr("Mouse entered the snail!")

func on_mouse_exited() -> void:
	# Reset the cursor to the default
	mouse_over = false
	CursorMgr.reset_cursor()