extends KinematicBody


var health = 60
var speed = 120

var damage = preload("res://sounds/SFX/hurt/yesman_hurt.wav")
var fuse = preload("res://sounds/SFX/hurt/yesman_death.wav")
var aggro = preload("res://sounds/SFX/hurt/yesman_aggro.wav")
var explosion = preload("res://objects/Explosion.tscn")

var engaged = false
var alert = false

var target = null


func _process(delta):
	#Gravity
	move_and_collide(Vector3(0,-0.25,0))
	#Face player and move
	if engaged:
		look_at(target.translation,Vector3(0,1,0))
		if health >= 0:
			move_and_slide(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
					$Hurt.stream = aggro
					$Hurt.pitch_scale = rand_range(1,1.4)
					$Hurt.unit_db = 6
					$Hurt.unit_size = 5
					$Hurt.play()


func take_damage(amount, type = 0, source = null):
	if type == ext.DAMAGE_TYPES.FIRE:
		explode()
	
	if health > 0:
		if health-amount > 0:
			$Hurt.stream = damage
			$Hurt.pitch_scale = rand_range(0.8,1.2)
			$Hurt.unit_size = 1
			$Hurt.play()
		health -= amount
		if health <= 0:
			explode()


func _on_Attack_body_entered(body):
	if body != null and health > 0:
		if body.is_in_group("player"):
			explode()


func _on_Follow_body_entered(body):
	if body != null:
		if body.is_in_group("player"):
			target = body
			alert = true

func explode():
	$Sprite3D.modulate = Color.red
	$Hurt.stream = fuse
	$Hurt.unit_db = 6
	$Hurt.unit_size = 5
	$Hurt.pitch_scale = 1.8
	$Hurt.play()
	yield($Hurt, "finished")
	var newboom = explosion.instance()
	newboom.translation = translation
	get_parent().add_child(newboom)
	queue_free()
