extends KinematicBody

# stats
var curHp : int = 3
var maxHp : int = 3
 
# attacking
var damage : int = 1
var attackDist : float = 1.5
var attackRate : float = 1.0
 
# physics
var moveSpeed : float = 2.5
var gravity : float = 15.0
 
# vectors
var vel : Vector3 = Vector3()
 
# components
onready var timer = get_node("Timer")
export var player_path : NodePath 
onready var player = get_node(player_path)
onready var anim = get_node("Zombie_Male/AnimationPlayer")

func _ready ():
	# set the timer wait time
	timer.wait_time = attackRate
	timer.start()
	
# called every "attackRate" seconds
func _on_Timer_timeout ():

	# if we're within the attack distance - attack the player
	if translation.distance_to(player.translation) <= attackDist:
		anim.play("Punch")
		player.take_damage(damage)

# called 60 times a second
func _physics_process (delta):
	
	# get the distance from us to the player
	var dist = translation.distance_to(player.translation)
	
	# if we're outside of the attack distance, chase after the player
	if dist > attackDist:
		# calculate the direction between us and the player
		var dir = (player.translation - translation).normalized()
		vel.x = dir.x
		vel.z = dir.z
	
	# gravity
	vel.y -= gravity * delta
	
	# TODO better
	look_at(player.translation, Vector3.UP)
	rotation_degrees.x = 0
	rotation_degrees.y = rotation_degrees.y + 180
	rotation_degrees.z = 0
	
	# move towards the player
	vel = move_and_slide(vel, Vector3.UP)
	
	if is_on_floor():
		if anim.current_animation != "Punch" and anim.current_animation != "RecieveHit":
			if vel.length_squared() > 0:
				anim.play("Walk")
			else:
				anim.play("Idle")
	else:
		anim.play("RecieveHit")
	
		
# called when the player deals damage to us
func take_damage (damageToTake):

	curHp -= damageToTake
	
	anim.play("RecieveHit")

	# if our health reaches 0 - die
	if curHp <= 0:
		die()

# called when our health reaches 0
func die ():

	# destroy the node
	queue_free()
