extends Node2D

@onready var path_2d: Path2D = $Path2D

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]


func _ready() -> void:
	get_node("CanvasLayer/SidePanel").Update_Lifes(20)
	get_node("CanvasLayer/SidePanel").Update_Coins(2000)

#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 waves = [
	[10, 0.2, 0.8, 0.2, 0.0],	#wave 1
	[20, 0.4, 0.5, 0.5, 0.0],	#wave 2
	[30, 0.5, 0.4, 0.4, 0.1],	#wave 3
	[40, 0.8, 0.3, 0.2, 0.5],	#wave 4
	[50, 0.9, 0.1, 0.2, 0.7],	#wave 5
]

var currentwave = 0
var endwave = false

func _on_timer_timeout() -> void:
	if endwave:
		if not get_node("Path2D").get_children():
			endwave = false
			get_node("CanvasLayer/SidePanel").Update_waves(currentwave + 1) #updating waves
	else:
		spawnMonster()

func spawnMonster():
	currentwave = 0
	for w in waves:
		if w[0] > 0:
			if randf() < w[1]:			#chance of generating any kind of enemy
				w[0] -= 1
				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)
							path_2d.add_child(path)
							break
			break
		else:
			currentwave += 1
			endwave = true

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)
	
