
extends KinematicBody2D

const SPEED = 25.0

export var health = 0
export var ricocheting = true
export var armor_class = 10

var move = false
var path = []

onready var navpoly = get_parent().get_node("geometry/navigation")
onready var ray = get_node("gun/ray")
onready var gun = get_node("gun")
onready var gun_partice = get_node("gun/Particles2D")
onready var particle = get_node("particle")

var bullet = preload("res://scenes/items/enemy_bullet.scn")
var b_pos_changer = false
var shoot = false

func _fixed_process(delta):
	var cpos = get_pos()
	var dpos = Globals.get("PLAYER").get_pos()
	var dist = cpos.distance_to(dpos) 
	
	gun.look_at(dpos)
	
	if move:
		var p = navpoly.get_simple_path(cpos, dpos, true)
		path = Array(p)
		path.invert()
		if path.size() > 1:
			var to_walk = delta*SPEED
			while(to_walk > 0 and path.size() >= 2):
				var pfrom = path[path.size() - 1]
				var pto = path[path.size() - 2]
				var d = pfrom.distance_to(pto)
				if (d <= to_walk):
					path.remove(path.size() - 1)
					to_walk -= d
				else:
					path[path.size() - 1] = pfrom.linear_interpolate(pto, to_walk/d)
					to_walk = 0
			var atpos = path[path.size() - 1]
			move_to(atpos)
			if (path.size() < 2):
				path = []		
		if ray.is_colliding() and ray.get_collider() == Globals.get("PLAYER"):
			move = false
			shoot = true
			audio.play_sound("combine_beep")
	else:
		if !ray.is_colliding() or ray.get_collider() != Globals.get("PLAYER"):
			audio.play_sound("combine_beep_2")
			move = true
			shoot = false
			gun_partice.set_emitting(false)
	
	if shoot and get_node("bullet_timer").get_time_left() == 0:
		get_node("bullet_timer").start()
		var b = bullet.instance()
		var b_pos
		if  b_pos_changer:
			b_pos = get_node("gun/bullet_shoot_1").get_global_pos()
		else:
			b_pos = get_node("gun/bullet_shoot_2").get_global_pos()
		b_pos_changer = !b_pos_changer
		var rot = gun.get_rot() - PI/2
		b.set_pos(b_pos)
		b.set_rot(rot)
		get_parent().add_child(b)
		gun_partice.set_emitting(true)
		audio.play_sound("shoot_2")
		
func apply_damage(var touch_pos, var touch_rot, var damage, var delay):
	move_to(get_pos() + Vector2(8, 0).rotated(touch_rot))
	if damage>0:
		particle.set_param(0, rad2deg(touch_rot + PI/2))
		particle.set_emissor_offset(Vector2(0, touch_pos.y))
		particle.set_emitting(true)
		audio.play_sound("hurt")
		health -= damage
	if health <= 0:
		die()

func die():
	audio.play_sound("explosion_1")
	global.show_effect(get_pos(), 3, 1)
	queue_free()

func _on_notifier_enter_screen():
	if armor_class == 1:
		get_node("armor").show()
	audio.play_sound("alarm")
	set_fixed_process(true)
	move = true
