#*
#* 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,
	OBTAIN,
	COMPLETE
}

var board : QuestBoard

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


func _generate_name() -> String:
	return "Get a Quest"

func _enter() -> void:
	var brd = Guild.hall.board
	if !brd:
		printerr("Get a Quest: Board not found!")
		return
	board = brd
	queue = board.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 board == 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.OBTAIN:
			if wait_time_remaining:
				wait_time_remaining -= delta
				if wait_time_remaining <= 0:
					board.interaction_complete.connect(_on_interaction_complete)
					board.interact(agent, "quest")
					phase = Phases.OBTAIN
		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 get_quest():
	phase = Phases.OBTAIN
	wait_time_remaining = randf_range(2,5)
	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 board.busy:
			wait()
		else:
			get_quest()
	pass

func _on_interaction_complete() -> void:
	board.interaction_complete.disconnect(_on_interaction_complete)
	if agent.data.quest != null:
		agent.show_speech_bubble("happy", 1.5)
	else:
		agent.show_speech_bubble("angry", 1.5)
	queue.remove_member(agent)
	phase = Phases.COMPLETE
