extends Node

export (int) var level
export (int) var health
export (bool) var BTESTING
export (int) var score
export (bool) var newgame 
export (String) var shieldsready

signal levelcompleted
signal enemyremoved
signal shieldsReady

var laserscore = 0

var enemycount  
var enemystart 
var lazer = false
var screensize
var timer 
var swarming
var startswarm = false

func _ready():
	#level = 10
	#health = 2000
	$Player.HEALTH = 1
	$Player.LEVEL = 1
	randomize()
	swarming = false
	screensize = get_viewport_rect().size
	timer = get_node("SwarmTimer")
	timer.set_wait_time(10)
	timer.connect("timeout", self, "_on_SwarmTimer_timeout")
	
	init_game()
	newgame = true
	#startLevel(level)
	print("Btesting" + str(BTESTING))
	
func _process(delta):
	shieldsready = $Player.shieldsready
	if (lazer):
		$Player.TARGETX = $Emitter.position.x
		$Player.TARGETY = $Emitter.position.y
	else:
		var mouseposition = get_viewport().get_mouse_position()
		$Player.TARGETX = mouseposition.x
		$Player.TARGETY = mouseposition.y

	update()

	
func _on_Emitter_emitting():
	lazer = true
	#print("Laser lazering")


func _on_Emitter_endemitting():
	lazer = false
	

func _draw():
    #your draw commands here
	if lazer :
		var lasercolor = Color(0,0,255)
		var playnode = get_node("Player")
		var emitternode = get_node("Emitter")
		var playvector = Vector2(playnode.position.x,playnode.position.y)
		var emittervector = Vector2(emitternode.position.x,emitternode.position.y)
		draw_line(playvector, emittervector, lasercolor,3.0,true)
		
	
				
	if BTESTING == true :
		var lasercolor = Color(0,0,255)
		var playnode = get_node("Player")
		var playvector = Vector2(playnode.position.x,playnode.position.y)
		for N in get_children():
			if N.get_name().matchn("*enemy*"):
				#print(N.get_name())
				var enemytargetcolor = Color(255,0,0)
				var enemyvector =  Vector2(N.position.x,N.position.y)
				#N.set_linear_velocity(Vector2())
				#N.apply_impulse ( Vector2(), playvector )
				draw_line(playvector, enemyvector, enemytargetcolor,1.0,false)
		
func startLevel(flevel):
	## generate the enemies and start them off moving at a random speed
	timer.stop()
	timer.start()
	$Player.LEVEL = flevel
	var enemycountstart = flevel * 5
	for x in range(0, enemycountstart):
		var scene = load("res://Enemy.tscn")
		var enemyinstance = scene.instance()
		enemyinstance.set_name("Enemy")
		var direction = rand_range(0, 2 * PI)
		enemyinstance.rotation = direction
		enemyinstance.position.x = rand_range(0, screensize.x -10)
		enemyinstance.position.y = rand_range(0, screensize.y -10)
		enemyinstance.TARGETX = 0
		enemyinstance.TARGETY = 0 
		enemyinstance.SWARM = 0
		enemyinstance.DIE = 0
		enemyinstance.set_linear_velocity(Vector2(rand_range(enemyinstance.MIN_SPEED, enemyinstance.MAX_SPEED), 0).rotated(direction))
		add_child(enemyinstance)
	$Emitter.ALIVE = true

	
	
func init_game():
	
	## create static bodies to make the top and bottom to keep the RigidBody enemies on screen
	for boundx in range(0, screensize.x + 10, 10):
		var boundscene = load("res://bounds.tscn")
		var boundinstancetop = boundscene.instance()
		var boundinstancebot = boundscene.instance()
		boundinstancetop.position.x = boundx
		boundinstancetop.position.y = 20
		add_child(boundinstancetop)
		boundinstancebot.position.x = boundx
		boundinstancebot.position.y = screensize.y 
		add_child(boundinstancebot)
	## create static bodies to make the sides to keep the RigidBody enemies on screen
	for boundy in range(0 + 20 , screensize.y + 10, 10):
		var boundscene = load("res://bounds.tscn")
		var boundinstanceleft = boundscene.instance()
		var boundinstanceright = boundscene.instance()
		boundinstanceleft.position.x = 0
		boundinstanceleft.position.y = boundy
		add_child(boundinstanceleft)
		boundinstanceright.position.x = screensize.x 
		boundinstanceright.position.y = boundy
		add_child(boundinstanceright) 

func startnewgame():
	clear_enemies()
	level = 1
	health= 200
	laserscore = 0
	$Player.HEALTH = health 
	startLevel(level)
	
func clear_enemies():
	# looop through objects identify enemies and remove them - for starting a new game
	for N in get_children():
			if N.get_name().matchn("*enemy*"):
				if not N.get_name().matchn("*swarm*"):
					#print(N.get_name())
					N.queue_free()
					
func _on_Player_playerhit():
	if health > 0:
		health -= 1
	$Player.HEALTH = health
	if health < 1:
		$Emitter.ALIVE = false
	



func _on_Emitter_enemydestroyed():
	laserscore += 20
	

func _on_Enemy_enemydestroyed():
	enemycount -= 1
	print("Enemy Eliminated")


func _on_SwarmTimer_timeout():
	if swarming:
		swarming = false
	else:
		swarming = true
	#startswarm = true
	
		#print("Swarming!!!")
	var playnode = get_node("Player")
	var playvector = Vector2(playnode.position.x,playnode.position.y)
	for N in get_children():
		if N.get_name().matchn("*enemy*"):
			#print(N.get_name())
			if swarming:
				N.SWARM = 1
			else:
				N.SWARM = 0
			N.TARGETX = playnode.position.x
			N.TARGETY = playnode.position.y
				

	#print ("make the enemies speed up!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
	

func _on_Player_shieldsoff():
	pass # replace with function body


func _on_Player_shieldson():
	pass # replace with function body


func _on_TimerCheck_timeout():
	# loop through the object to get count of remaining enemies
	
	enemycount = 0
	for N in get_children():
			if N.get_name().matchn("*enemy*"):
				if not N.get_name().matchn("*swarm*"):
					#print(N.get_name())
					enemycount += 1
					
	score = laserscore
	if newgame:
		newgame = false
		startnewgame()
	elif enemycount == 0:
		level += 1
		startLevel(level)
	
