
extends StaticBody2D

const ROTATION_SPEED = 2

export var health = 0
export var armor_class = 3
export var ricocheting = true
export var placeholder = false

var siding_left = false
var bullet = preload("res://scenes/items/plasma_bullet.scn")
var shooting = false

onready var gun = get_node("main/gun")
onready var ray = get_node("main/gun/ray")
onready var head = get_node("main/head")
onready var gun_partice = get_node("main/gun/Particles2D")
onready var offset = Vector2(0, 0)
onready var particle = get_node("hurt_particle")

func _draw():
	if get_node("main/gun/ray").is_colliding():
		var gpos = get_global_pos()
		var point = get_node("main/gun/ray").get_collision_point() - gpos
		draw_line(get_node("main/gun/laser_point").get_global_pos() - gpos, point, Color(0.8, 0.1, 0.1), 2)

func _fixed_process(delta):
	
	var new_siding_left = siding_left
	
	var ppos = Globals.get("PLAYER").get_pos()
	var pos = get_pos()
	var rpos = pos - ppos
	
	head.look_at(ppos)
	
	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)
	
	var can_shoot = ray.is_colliding() and ray.get_collider() == Globals.get("PLAYER")
	
	if can_shoot and get_node("bullet_timer").get_time_left() == 0:
		get_node("bullet_timer").start()

	if rpos.x > 0:
		new_siding_left = true
	else:
		new_siding_left = false
		
	if (new_siding_left!=siding_left):
		if (new_siding_left):
			get_node("main").set_scale(Vector2(-1,1))
		else:
			get_node("main").set_scale(Vector2(1,1))
		siding_left=new_siding_left	
	update()

func _shoot():
	shooting = true
	get_node("shoot_delay").start()
	yield(get_node("shoot_delay"), "timeout")
	var b = bullet.instance()
	var b_pos = get_node("main/gun/bullet_shoot").get_global_pos()
	var rot = gun.get_rot()+PI/2
	b.set_pos(b_pos)
	if siding_left:
		b.set_rot(-rot)
	else:
		b.set_rot(rot-PI)
	get_parent().add_child(b)
	gun_partice.set_emitting(true)
	gun.rotate(0.5)
	audio.play_sound("shoot_3")
	shooting = false
	
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():
	queue_free()
#	get_node("anim").play("death")
	audio.play_sound("explosion_10")
	global.show_effect(get_pos(), 2, 1)
	global.show_effect(get_pos(), 1, 1)

func _ready():
	pass

func _on_enabler_enter_screen():
	set_fixed_process(true)
