extends Node2D

var  paths = []
var waves = []

const FORKMAN = preload("res://Game/Mobs/forkman.tscn")
const ORK = preload("res://Game/Mobs/ork.tscn")
const COBOLD = preload("res://Game/Mobs/cobold.tscn")

const enemies = [FORKMAN, COBOLD, ORK]

var pause = 40
func _ready() -> void:
	get_node("CanvasLayer/SidePanel").set_Lifes(get_node("Setup").lives)
	get_node("CanvasLayer/SidePanel").Update_Coins(get_node("Setup").coins)
	for i in self.get_children():
		if i.name.contains("Path2D"):
			paths.append(i)
	waves = get_node("Setup").waves

#the meaning of the columns inside my wave generation matris:
# Number of enemies need to be spawned, chance of spawn an enemy, chance of forkman, chance of gobline, chance of ork

var currentwave = 0
var endwave = false


func _on_timer_timeout() -> void:
	if pause <= 0:
		if endwave:
			var checkend = false
			for i in paths:
				if i.get_children():
					break
				checkend = true
				currentwave += 1
				break
			if checkend:
				endwave = false
				get_node("CanvasLayer/SidePanel").Update_waves(currentwave + 1) #updating waves
				pause = 40
				if currentwave >= waves[0].size():
					get_node("CanvasLayer/SidePanel").Update_waves(currentwave) #updating waves
					get_node("Timer").stop()
					get_node("CanvasLayer/SidePanel").GameWon()
		else:
			spawnMonster()
	else:
		pause -= 1

func spawnMonster():
	for ROUTE in range(waves.size()):
			var w = waves[ROUTE][currentwave]
			if w[0] > 0:
				if randf() < w[1]:
					w[0] -= 1
					for i in waves:
						if i[currentwave][0] > 0:
							break
						endwave = true
					var chosen = randf()
					var sum = 0.0
					for i in range(2,5):
						sum += w[i]
						if chosen < sum:
								var monster = enemies[i-2].instantiate()
								var path = PathFollow2D.new()
								path.add_child(monster)
								paths[ROUTE].add_child(path)
								break


func decrease_life(damage) -> void:
	get_node("CanvasLayer/SidePanel").Update_Lifes(-damage)
	if get_node("CanvasLayer/SidePanel").get_Lifes() <= 0:
		game_over()


func game_over()-> void:
	get_node("Timer").stop()
	var enemy = get_node("Path2D").get_children()
	for i in enemy:
		i.get_children()[0].set_process(false)
	
