extends Node2D
@onready var obstaclesSpawnTimer = $obstaclesSpawnTimer

@onready var shotgunEnemy: PackedScene = preload("res://scenes/spaceShip/enemy/shotgunEnemy/shotgunEnemy.tscn")
@onready var minigunEnemy: PackedScene = preload("res://scenes/spaceShip/enemy/minigunEnemy/minigunEnemy.tscn")
@onready var railgunEnemy: PackedScene = preload("res://scenes/spaceShip/enemy/railgunEnemy/railgunEnemy.tscn")
@onready var meteor: PackedScene = preload("res://scenes/obstacle/meteor/meteor.tscn")
@onready var radiation: PackedScene = preload("res://scenes/obstacle/radiation/radiation.tscn")

@onready var endScreen: PackedScene = preload("res://scenes/UI/loseScreen/endScreen.tscn")

var minigunRatio = 5
var railgunRatio = 10
var endedRound = false

@onready var player = $Player

func _ready() -> void:
	obstaclesSpawnTimer.autostart = true
	obstaclesSpawnTimer.start()
	Globals.setPlayer(player)
	Globals.waveComplete.connect(nextWave)
	player.destroyed.connect(endRound)
	nextWave()


func spawnObstacle(_obstacle: PackedScene, _position: Vector2):
	var newObstacle = _obstacle.instantiate()
	newObstacle.global_position = _position
	if get_tree().get_first_node_in_group("obstaclePool") != null:
		get_tree().get_first_node_in_group("obstaclePool").add_child(newObstacle)

func spawnEnemy(_enemy: PackedScene, _position: Vector2):
	Globals.enemyCount += 1
	var newEnemy = _enemy.instantiate()
	newEnemy.global_position = _position
	if get_tree().get_first_node_in_group("enemyPool") != null:
		get_tree().get_first_node_in_group("enemyPool").add_child(newEnemy)

	#newEnemy.destroyed.connect(startEnemySpawnTimer)

func _on_obstacles_spawn_timer_timeout() -> void:
	var rng = RandomNumberGenerator.new()
	var number = rng.randi_range(0, 10)
	if number == 10:
		if Globals.getPlayer() != null:
			spawnObstacle(radiation, Globals.getPlayer().getRandomSpawnPointPosition())
	else:
		if Globals.getPlayer() != null:
			spawnObstacle(meteor, Globals.getPlayer().getRandomSpawnPointPosition())


func nextWave():
	Globals.enemyCount = 0
	Globals.currentWave += 1
	if Globals.getPlayer() != null:
		for i in range(1, Globals.currentWave+1):
			if i % railgunRatio == 0:
				spawnEnemy(railgunEnemy, Globals.getPlayer().getRandomSpawnPointPosition())
			elif i % minigunRatio == 0:
				spawnEnemy(minigunEnemy, Globals.getPlayer().getRandomSpawnPointPosition())
			else:
				spawnEnemy(shotgunEnemy, Globals.getPlayer().getRandomSpawnPointPosition())

func endRound():
	if not endedRound:
		endedRound = true
		get_tree().get_root().add_child(endScreen.instantiate())
		self.queue_free()
