extends Node2D
class_name Dog

@onready var death_box = $DeathBox
@onready var outline = $AreaHighlight

var acquired_target : Bee = null 
var target_timer : float = 0.0
@export var distracted : bool = false
var distracted_by : Node2D = null

func _ready():
	death_box.connect("body_entered", Callable(self, "_on_body_entered"))
	death_box.connect("body_exited", Callable(self, "_on_body_exited"))

func _process(delta):
	if acquired_target:
		target_timer += delta

		# Look at the target 
		rotation = lerp_angle(rotation, rotation + get_angle_to(acquired_target.global_position), 0.5)

		if target_timer > 3.0:
			# Kill the target!
			acquired_target.die()
			acquired_target = null
			target_timer = 0.0
			return 		


	if distracted_by:
		# Look around
		rotation = lerp_angle(rotation, rotation + get_angle_to(distracted_by.global_position), 0.5)

func show_outline():
	outline.visible = true

func hide_outline():
	outline.visible = false	


func _on_body_entered(area):
	if area.is_in_group("bee") and distracted == false:
		if !acquired_target:
			Log.pr("Acquired target")
			target_timer = 0.0
			acquired_target = area

	if area.is_in_group("distractor"):
		Log.pr("Distracted")
		acquired_target = null
		distracted = true
		distracted_by = area

func _on_body_exited(area):
	if area == acquired_target:
		Log.pr("Lost target")
		acquired_target = null
		target_timer = 0.0

	if area.is_in_group("distractor"):
		Log.pr("No longer distracted")
		distracted = false
		distracted_by = null
