#*
#* use_guild_service.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,
	SERVICE,
	COMPLETE
}

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

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

var employee : GuildEmployee
var queue : GuildQueue
var wait_time_remaining : float = 0
var phase : Phases


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

func _enter() -> void:
	var emp = Guild.hall.employees.get(employee_name)
	if !emp:
		printerr("Use Guild Service (%s) - %s, '%s' not found!", employee_name, service_name, employee_name)
		return
	employee = emp
	queue = employee.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 employee == 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.SERVICE:
			if wait_time_remaining > 0:
				wait_time_remaining -= delta
				if wait_time_remaining <= 0:
					employee.service_provided.connect(_on_service_complete)
					employee.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 use_service():
	phase = Phases.SERVICE
	wait_time_remaining = randf_range(2,5)
	agent.show_speech_bubble("talk")
	employee.show_speech_bubble("talk")

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 employee.busy:
			wait()
		else:
			use_service()
	pass

func _on_service_complete() -> void:
	employee.service_provided.disconnect(_on_service_complete)
	agent.show_speech_bubble("")
	employee.show_speech_bubble("")
	queue.remove_member(agent)
	phase = Phases.COMPLETE
	
