class_name Player extends Person

const marker_template = preload("res://templates/move_marker.tscn")
@onready var movement_speed : float = 400.0
@onready var movement_target_position : Vector2 = global_position
@onready var nav_agent : NavigationAgent2D = $NavigationAgent2D

var interaction_target = null
var marker = null
@export var interaction_range : float = 75
@export var stop_range : float = 25
var data : Adventurer

func _ready() -> void:
	Game.player = self
	data = Adventurer.new()
	data.life = 20
	data.max_life = 20
	data.inventory_size = Vector2(4,2)
	data.name = "Player"
	setup.call_deferred()


func setup():
	await get_tree().physics_frame
	set_movement_target(movement_target_position)


func set_movement_target(target : Vector2) -> void:
	nav_agent.target_position = target

func _physics_process(delta: float) -> void:
	
	if nav_agent.is_navigation_finished():
		if marker != null:
			marker.visible = false
		if interaction_target:
			try_interact(interaction_target)
		#If they have an interaction target within range
			#clear the target
			#try_interact 
		return
	
	var curr_pos: Vector2 = global_position
	var next_path_pos: Vector2 = nav_agent.get_next_path_position()
	
	velocity = curr_pos.direction_to(next_path_pos) * movement_speed
	
	move_and_slide()
	
func _unhandled_input(event: InputEvent) -> void:
	var evt : InputEventMouseButton = event as InputEventMouseButton
	if evt and evt.pressed:
		approach(evt.global_position)
		nav_agent.target_desired_distance = stop_range
		interaction_target = null

func approach(pos : Vector2) -> void:
	if marker == null or !is_instance_valid(marker):
		marker = marker_template.instantiate()
		Guild.hall.add_child(marker)
	var rid = get_world_2d().get_navigation_map()
	var point : Vector2 = NavigationServer2D.map_get_closest_point(rid, pos)
	marker.global_position = point
	marker.visible = true
	set_movement_target(point)
	
func approach_and_interact(obj : Interactable) -> void:
	var t : Vector2 = obj.global_position
	if "queue" in obj and obj.queue != null:
		t = obj.queue.global_position
	set_movement_target(obj.global_position)
	nav_agent.target_desired_distance = interaction_range - 5
	interaction_target = obj

func try_interact(obj : Interactable) -> void:
	var df = obj.global_position - global_position
	if df.length() > interaction_range:
		approach_and_interact(obj)
	else:
		interact(obj)
		interaction_target = null

func interact(obj : Interactable) -> void:
	obj.interact(self)
