#*
#* use_guild_equipment.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].


enum Phases {
	ARRIVE,
	QUEUE,
	WAIT,
	INTERACT,
	COMPLETE
}

## Blackboard variable that stores the target position (Vector2)
@export var equipment_name : String = ""

## Variable that stores desired speed (float)
@export var service_name : String = ""

var equipment : Interactable
var queue : GuildQueue
var wait_time_remaining : float = 0
var phase : Phases


func _generate_name() -> String:
	return "Use Guild Equipment (%s) - %s" % [
		equipment_name,
		service_name
	]

func _enter() -> void:
	var eq = Guild.hall.interactables.get(equipment_name)
	if !eq:
		printerr("Use Guild Equipment (%s) - %s, '%s' not found!" % [equipment_name, service_name, equipment_name])
		return
	equipment = eq
	queue = equipment.queue
	phase = Phases.ARRIVE
	queue.add_member(agent)
	agent.approach(queue.get_last_position())
	agent.navigation_finished.connect(_on_navigation_complete)
	agent.navigation_failed.connect(_on_navigation_failed)
	
func _tick(delta: float) -> Status:
	if equipment == null:
		return FAILURE
	match(phase):
		Phases.ARRIVE:
			if wait_time_remaining > 0:
				wait_time_remaining -= delta
				if wait_time_remaining <= 0:
					agent.navigation_finished.connect(_on_navigation_complete)
					agent.approach(queue.get_member_position(agent))
		Phases.QUEUE:
			pass
		Phases.WAIT:
			pass
		Phases.INTERACT:
			if wait_time_remaining > 0:
				wait_time_remaining -= delta
				if wait_time_remaining <= 0:
					equipment.interaction_complete.connect(_on_interaction_complete)
					equipment.interact(agent, service_name)
		Phases.COMPLETE:
			return SUCCESS
	return RUNNING

func _on_navigation_complete() -> void:
	agent.navigation_finished.disconnect(_on_navigation_complete)
	agent.navigation_failed.disconnect(_on_navigation_failed)
	queue.advanced.connect(_on_queue_advanced)
	phase = Phases.QUEUE

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)

func interact():
	phase = Phases.INTERACT
	wait_time_remaining = randf_range(2,5)
	equipment.busy = true
	agent.show_speech_bubble("busy")

func wait():
	wait_time_remaining = 1
	phase = Phases.WAIT
	

func _on_queue_advanced() -> void:
	if queue.front == agent:
		queue.advanced.disconnect(_on_queue_advanced)
		if equipment.busy:
			wait()
		else:
			interact()
	pass

func _on_interaction_complete() -> void:
	equipment.interaction_complete.disconnect(_on_interaction_complete)
	equipment.busy = false
	agent.show_speech_bubble("")
	queue.remove_member(agent)
	phase = Phases.COMPLETE
	
	
