class_name Human
extends CharacterBody2D

@export var speed = 250 # How fast the player will move (pixels/sec).

# intensions of the player turner into a boolean
@export var wants_to_grab = false;
var wants_to_interact_with: Node2D
var humanInteractionTarget: Human = null

@onready var animation_tree := $AnimationTree
@onready var animation_player := $AnimationPlayer
@onready var state_machine := animation_tree.get("parameters/HumanState/playback") as AnimationNodeStateMachinePlayback
@onready var interactionZone : InteractionZone = $"interaction zone"

signal start_intracting

var last_facing_direction = Vector2(0,1) # facing south
var velocityVector = Vector2(0, 0)
var targetGlobalPosition = null

func moveTo(p: Vector2) -> void:
	targetGlobalPosition = p

func moveFeetTo(p: Vector2) -> void:
	targetGlobalPosition = p - Vector2(0, 43)
	
func face(whereToFace: Vector2) -> void:
	last_facing_direction = (whereToFace - global_position).normalized()
		
func decideAction() -> void:
	pass

func updateFacingDirectionInAnimationTree():
	animation_tree.set("parameters/HumanState/grabing/blend_position", last_facing_direction)
	animation_tree.set("parameters/HumanState/idling/blend_position", last_facing_direction)
	animation_tree.set("parameters/HumanState/walking/blend_position", last_facing_direction)

func _physics_process(delta):
	decideAction()

	if (targetGlobalPosition != null):
		velocity = (targetGlobalPosition - global_position).normalized() *speed
		targetGlobalPosition = null
	else:
		velocity = velocityVector * speed

	if state_machine.get_current_node() == "grabing" or humanInteractionTarget != null :
		velocity = Vector2(0,0);

	# move the caracter
	move_and_slide()

	# compute the direction the player wants to look at
	if velocity:
		last_facing_direction = velocity.normalized()

	updateFacingDirectionInAnimationTree()
	
	if wants_to_interact_with and wants_to_interact_with.has_method("start_interaction"):
		if humanInteractionTarget == null:
			humanInteractionTarget = wants_to_interact_with as Human
			humanInteractionTarget.start_interaction(self)

func _on_area_2d_body_entered(body: Node2D) -> void:
	print(body)
	
func start_interaction(askingForInteraction: Human):
	emit_signal("start_intracting", askingForInteraction)
	disable_interaction_clue()

func stop_interaction():
	humanInteractionTarget = null
	
func get_feet_global_position():
	return global_position + Vector2(0, 43)
	
func enable_interaction_clue(from: Human):
	if interactionZone:
		var mat = $Sprite2D.get("material") as ShaderMaterial
		if mat:
			mat.set_shader_parameter("line_thickness", 1)
		interactionZone.enable_interaction_clue(from)
	
func disable_interaction_clue():
	if interactionZone:
		var mat = $Sprite2D.get("material") as ShaderMaterial
		if mat:
			mat.set_shader_parameter("line_thickness", 0)
		interactionZone.disable_interaction_clue()
