extends Node2D
class_name Flowers

@onready var outline : Sprite2D = $AreaHighlight

@export var health : int = 100

var spawn_snails : bool = false

@onready var spawn_area : CollisionShape2D = $FlowerCollectionArea/CollisionShape2D
@onready var snail : Snail = $Snail

var last_health_check : float = 0
var health_check_timer : float = 0.5

@onready var health_bar : ProgressBar = $HealthBar

func _ready() -> void:
	hide_outline()
	setup_healthbar()

	## Check if this level is spawning snails or not 
	if GameState.spawn_snails:
		Log.pr("Going to be spawning snails!")
		spawn_snails = true

	Log.pr(get_random_circumference_points())
	snail.global_position = get_random_circumference_points()

func _process(delta: float) -> void:
	update_healthbar(delta)

func show_outline() -> void:
	outline.visible = true

func hide_outline() -> void:
	outline.visible = false


func get_random_circumference_points() -> Vector2:
	var circle_radius : float = spawn_area.shape.radius
	var random_angle : float = randf_range(0, TAU)

	var x : float = circle_radius * cos(random_angle)
	var y : float = circle_radius * sin(random_angle)

	var circle_center : Vector2 = spawn_area.global_position
	var random_point : Vector2 = circle_center + Vector2(x, y)

	return random_point

## Initial setup of the health bar - updating the values 
# and hiding it from view.
func setup_healthbar() -> void:
	health_bar.max_value = GameState.max_flower_nectar_level
	health_bar.value = GameState.flower_nectar_level
	health_bar.visible = false

## Update the health bar based on the current GameState values 
# and display it if required. Conversely, hide it if the flower is at max powah.
func update_healthbar(delta : float) -> void:
	last_health_check += delta
	if last_health_check >= health_check_timer:
		last_health_check = 0
		if GameState.flower_nectar_level < GameState.max_flower_nectar_level:
			health_bar.value = GameState.flower_nectar_level
			health_bar.visible = true
		else:
			health_bar.value = GameState.max_flower_nectar_level
			health_bar.visible = false