extends Node2D

var waves = [{i = 0, n = 32, t = 0.8, bc = 7},
			 {i = 1, n = 4, t = 4, bc = 0}, 
			 {i = 0, n = 32, t = 0.4, bc = 9}, 
			 {i = 2, n = 1, t = 1, pos = Vector2(16, -4), bc = 9}]

var _wave = 0
var dx = 1
var game = false
var n = 16 setget n_set
func n_set(new_value):
	n = new_value
	$gul/wavebar.value = n

var bonuses = ["support", "rockets", "hp"]

onready var enemie_0_scene = load("res://scenes/enemie_0.tscn")
onready var enemie_1_scene = load("res://scenes/enemie_1.tscn")
onready var enemie_2_scene = load("res://scenes/enemie_2.tscn")
onready var bonus_scene = load("res://scenes/bonus.tscn")

onready var enemies = [enemie_0_scene, enemie_1_scene, enemie_2_scene]

func flash():
	$effect/anim.play("flash")
	
func damage():
	$effect/anim.play("damage")
	
func queue():
	pass
	
func wave():
	var w = waves[_wave]
	var i = w.i
	$spawn_time.wait_time = w.t
	var p = Vector2()
	var bonus_chance = w.bc
	n = w.n
	$gul/wavebar.max_value = n
	$gul/wavebar.value = n
	if n > 1:
		while n > 0:
			spawn_enemie(i, p, dx)
			dx *= -1
			if randi() % 11 > bonus_chance:
				spawn_bonus(bonuses[randi() % 3])
			$spawn_time.start()
			yield($spawn_time, "timeout")
	elif n == 1:
		p = w.pos
		spawn_enemie(i, p, 1)
		while n > 0:
			if randi() % 11 > bonus_chance:
				spawn_bonus(bonuses[randi() % 3])
			$spawn_time.start()
			yield($spawn_time, "timeout")
			
	var timer = _create_timer(1)
	yield(timer, "timeout")
	timer.queue_free()

	_wave += 1
	if _wave != waves.size():
		wave()
	else:
		next_level()
		
func _create_timer(t):
	var _timer = Timer.new()
	_timer.wait_time = t
	_timer.one_shot = true
	add_child(_timer)
	_timer.start()
	return _timer

func spawn_enemie(id, p, d):
	var pos
	if p ==Vector2():
		pos = Vector2(randi() % 31, -4)
	else: 
		pos = p
	var e = enemies[id].instance()
	e.dir_x = d
	e.position = pos
	add_child(e)
	
func spawn_bonus(_n):
	var bonus = bonus_scene.instance()
	var pos = Vector2((randi() % 30) + 1, -2)
	bonus.bonus_name = _n
	bonus.position = pos
	add_child(bonus)
	
func restart():
	game = false
	var timer = _create_timer(3)
	yield(timer, "timeout")
	timer.queue_free()
	var _err = get_tree().reload_current_scene()
	
func next_level():
	$fader/anim.play("fade_in")
	yield($fader/anim, "animation_finished")
	var _err = get_tree().change_scene("res://scenes/final_screen.tscn")
	
func _ready():
	randomize()
	$fader/anim.play("fade_out")
	var timer = _create_timer(1)
	yield(timer, "timeout")
	wave()
	timer.queue_free()
	game = true
