
extends StaticBody2D

const ROTATION_SPEED = 1.5

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

onready var ray = get_node("gun/ray")
onready var gun = get_node("gun")
onready var gun_partice = get_node("gun/particle")
onready var particle = get_node("hurt_particle")

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


func _fixed_process(delta):
	
	var ppos = Globals.get("PLAYER").get_pos()
	var pos = get_pos()
#	var rpos = pos - ppos	
	if pos.distance_to(ppos)>200:
		shooting = false
		
	if !shooting:
		var ang = gun.get_angle_to(ppos)
		var s = sign(ang)
		ang = abs(ang)
		var rot = min(ang, ROTATION_SPEED*delta)*s
		gun.rotate(rot)
		
	elif 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_3")
	
#	var can_shoot = ray.is_colliding() and ray.get_collider() == Globals.get("player")
func _on_shoot_delay_timeout():
	shooting = true
	get_node("anim").play("shooting")
	
func _on_anim_finished():
	if !destroyed:
		shooting = false
		get_node("shoot_delay").start()
	
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:
#		get_node("damage_anim").play("hurt_anim")
		particle.set_emitting(true)
		audio.play_sound("hurt")
		health -= damage
	if health <= 0:
		die()
		
func die():
	destroyed = true
	shooting = false
	get_node("shoot_delay").stop()
	get_node("anim").play("destroyed")
	set_fixed_process(false)
#	queue_free()
	get_node("coll").free()	
	audio.play_sound("explosion_6")
	global.show_effect(get_pos(), 1, 1)
	get_node("smoke").set_emitting(true)

func _on_notifier_enter_screen():
	get_node("shoot_delay").start()
	set_fixed_process(true)
