extends KinematicBody


var health = 45
var speed = 1.1

var damage = preload("res://sounds/SFX/hurt/crabhead_hurt.wav")

var target = null

var alert = false
var engaged = false


func _process(delta):
	#Gravity
	move_and_collide(Vector3(0,-0.25,0))
	#Face the player and follow them
	if engaged:
		look_at(target.translation,Vector3(0,1,0))
		if health >= 0:
			move_and_collide(transform.basis.xform(Vector3(0,0,-1.5))*(speed*delta))
			
	#Establish a line of sight with the player before attacking
	if alert and !engaged:
		$RayCast.enabled = true
		$RayCast.cast_to = target.translation - translation
		if $RayCast.is_colliding():
			if $RayCast.get_collider() != null:
				if $RayCast.get_collider().is_in_group("player"):
					target = $RayCast.get_collider()
					engaged = true
					$RayCast.enabled = false


func take_damage(amount, type = 0, source = null):
	if health > 0:
		$Hurt.pitch_scale = rand_range(0.8,1.2)
		$Hurt.stream = damage
		$Hurt.play()
		health -= amount
		if health <= 0:
			#print("i have died")
			$Sprite3D.modulate = Color.red
			yield($Hurt, "finished")
			queue_free()


func _on_Attack_body_entered(body):
	if body != null and health > 0:
		if body.has_method("take_damage") and !body.is_in_group("crabhead"):
			body.take_damage(12+randi()%15, ext.DAMAGE_TYPES.MELEE, self)
			
			
func change_color(new_color):
	$Sprite3D.modulate = new_color


func _on_Aggro_body_entered(body):
	if body.is_in_group("player"):
		target = body
		alert = true
