extends AbstractPrey

@onready var wrapper: WrappingManager = $WrappingManager
@onready var collision: CharacterBody2D = $Collision
@onready var sprite: AnimatedSprite2D = $"Collision/Sprite"
@onready var fsm: StateMachine = $StateMachine
var starting_pos

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	health = maxHealth
	sprite.play("Healthy")
	wrapper.play_sprite("Healthy")
	if starting_pos:
		collision.set_position(starting_pos)

func set_position(pos: Vector2) -> void:
	if collision:
		collision.set_position(pos)
	else:
		starting_pos = pos
	
func move(motion: Vector3, mod: float = 1.0) -> void:
	collision.move(motion, mod)

func handle_damage(dmg: int, src: Node) -> void:
	health = max(0, health-dmg)
	if health == 0:
		die()
	if health < maxHealth:
		become_injured()
	fsm.transition_to_next_state(fsm.States.FLEEING, {"threat": src})
	
func die() -> void:
	sprite.play("Dying")
	wrapper.play_sprite("Dying")
	GameManager.foodManager._spawn_food(collision.position)
	super.die()

func become_injured() -> void:
	sprite.play("Injured")
	wrapper.play_sprite("Injured")

func _on_sight_body_entered(body: Node2D) -> void:
	if body.is_in_group("predator") or (health < maxHealth and body.is_in_group("player")):
		fsm.transition_to_next_state(fsm.States.FLEEING, {"threat": body})
