extends RigidBody2D

export (int) var MIN_SPEED
export (int) var MAX_SPEED
export (float) var TARGETX
export (float) var TARGETY
export (int) var SWARM
export (int) var DIE


var screensize
var sample_player 
var timer 
var isalive = true
var game 

func _ready():
	screensize = get_viewport_rect().size
	timer = get_node("TimetoDie")
	timer.set_wait_time(.4)
	timer.connect("timeout", self, "_on_TimetoDie_timeout")
	

func _process(delta):
	if isalive:
		if DIE > 0:
			isalive = false
			die()
	
	
func _integrate_forces(state):
	
	if SWARM > 0:
		#$Label.text = "Swarm On"
		#print ("Swarm" + self.get_name())
		var thrust = Vector2(0,250)
		var aoa = getAOA(position.x,position.y, TARGETX, TARGETY)
		set_applied_force(thrust.rotated(aoa + PI/2))
	else: 
		$Label.text = ""
	#set_applied_torque(rotation_dir * spin_thrust)
	var xform = state.get_transform()
	if xform.origin.x > screensize.x:
		xform.origin.x = 0
	if xform.origin.x < 0:
		xform.origin.x = screensize.x
	if xform.origin.y > screensize.y:
		xform.origin.y = 0
	if xform.origin.y < 0:
		xform.origin.y = screensize.y
	
	state.set_transform(xform)

func getAOA(x,y,tx,ty):
	#baseAngle = 0
	#hypopp =  abs(x-tx)
	var a = Vector2(x,y)
	var b = Vector2(tx,ty)
	return a.angle_to_point(b)

func _on_Enemy_body_entered(body):
	#print("Enemyhit!")
	#print(body.get_name())
	if body.get_name().matchn("*shield*"):
		print("Enemyhit! ------ shield")
		emit_signal("enemydies")
		die()
	if body.get_name().matchn("*enemy*"):
		$ASP2D_collide.play();


func die():
	$AnimatedSprite.play("explode")
	$ASP2D_eliminate.play()
	timer.start()

func _on_TimetoDie_timeout():
	print(self.get_name() + "..Die!!!")
	self.queue_free()
	