#*
#* go_to.gd
#*
@tool
extends BTAction
## Moves the agent to the specified position, favoring horizontal movement. [br]
## Returns [code]SUCCESS[/code] when close to the target position (see [member tolerance]);
## otherwise returns [code]RUNNING[/code].

## Blackboard variable that stores the target position (Vector2)
@export var target_position_var := &"pos"
var wait_time_remaining : float = 0
var goal_position : Vector2

var done : bool

func _generate_name() -> String:
	return "Go to Position: %s" % [LimboUtility.decorate_var(target_position_var)]

func _enter() -> void:
	done = false
	goal_position = blackboard.get_var(target_position_var, Vector2.ZERO)
	go_to(goal_position)

func _tick(delta: float) -> Status:
	if done:
		return SUCCESS
	#If we were interrupted, wait a little bit and try again
	if wait_time_remaining > 0:
		wait_time_remaining -= delta
		if wait_time_remaining <= 0:
			go_to(goal_position)
	return RUNNING

func go_to(pos : Vector2) -> void:
	agent.navigation_finished.connect(_on_navigation_complete)
	agent.navigation_failed.connect(_on_navigation_failed)
	agent.approach(pos)
	
func _on_navigation_complete() -> void:
	agent.navigation_finished.disconnect(_on_navigation_complete)
	agent.navigation_failed.disconnect(_on_navigation_failed)
	done = true

func _on_navigation_failed() -> void:
	wait_time_remaining = randf_range(.5, 2)
	agent.navigation_finished.disconnect(_on_navigation_complete)
	agent.navigation_failed.disconnect(_on_navigation_failed)
