extends Node3D

@onready var game_over_screen = $GameOverScreen/PanelContainer
@onready var game_over_score = $GameOverScreen/PanelContainer/MarginContainer/Rows/score
@onready var EnemyHolder = $Terrain/NavigationRegion3D/StaticBody3D/SpawnedObjects
@onready var worldGenerator = $Terrain/NavigationRegion3D/StaticBody3D
@onready var HUD = $HUD

var player = null;
@export var MaxEnemyCount = 20.0;
@export var MinEnemyTreshold = 8.0;

@export var kill_score = 0;
var xp = 0;
var xp_to_levelup = 10;
var xp_to_another = 5;

@export var MinEnemyCountDifficultyMultiplayer = 42.0;
@export var MaxEnemyCountDifficultyMultiplayer = 80.0;

var enemy_count: int = 0;

# Called when the node enters the scene tree for the first time.
func _ready():
	player = get_tree().get_first_node_in_group("Player")
	player.player_died.connect(_on_player_killed)
	enemy_count = 0


func _process(delta):	
	# Check the current number of enemies
	if not worldGenerator.generated_terain:
		return
	var currentEnemies = enemy_count
	# print(currentEnemies)
	
	var minEnemyTreshold: int = MinEnemyTreshold + HUD.get_difficulty_multiplayer() * MinEnemyCountDifficultyMultiplayer
	var maxEnemyTreshold: int = MaxEnemyCount + HUD.get_difficulty_multiplayer() * MaxEnemyCountDifficultyMultiplayer
	
	# Spawn a new enemy if there are fewer than 3
	if enemy_count < minEnemyTreshold:
		for i in randi() % (maxEnemyTreshold - enemy_count):
			spawn_enemy()
			enemy_count += 1


func _on_player_killed():
	await get_tree().create_timer(.3).timeout
	game_over_score.text = "score: " + str(kill_score);
	HUD.countdown = false
	game_over_screen.visible = true
	
	# stop all enemies
	for i in range(EnemyHolder.get_child_count()):
		var child = EnemyHolder.get_child(i)
		if child is Enemy or child is Wolf:
			child.speed = 0
			child.attack_distace = 0


func update_kill_score(gained_score: int):
	enemy_count -= 1
	kill_score += gained_score;
	HUD.add_xp(gained_score);
	$HUD/TextEdit.text = "score: " + str(kill_score);


var enemySceneWolf = preload("res://Scenes/Enemies/wolf.tscn")  # Path to Enemy scene
var enemySceneBabyWolf = preload("res://Scenes/Enemies/baby_wolf.tscn")
var enemySceneCavemen = preload("res://Scenes/Enemies/enemy.tscn")
var enemySceneRat = preload("res://Scenes/Enemies/rat.tscn")
var enemySceneTurtle = preload("res://Scenes/Enemies/turtle.tscn")
var enemyScenes = [enemySceneWolf, enemySceneBabyWolf, enemySceneCavemen, enemySceneRat, enemySceneTurtle]

func count_enemies():
	var enemy_count = 0
	# Later might want to use signals when something dies, 
	# instead of always looping through 
	for i in range(EnemyHolder.get_child_count()):
		var child = EnemyHolder.get_child(i)

		if child is Enemy or child is Wolf:
			enemy_count += 1

	return enemy_count


func spawn_enemy_instance(newEnemy, distance):
	EnemyHolder.add_child(newEnemy)
	newEnemy.update_stats(HUD.get_difficulty_multiplayer())
	newEnemy.position = Vector3(randi() % 70 - 35, 20 + distance*2, randi() % 70 - 35)
	return
	while true:
		# Set a random position for the new enemy
		newEnemy.position = Vector3(randi() % 800, 10, randi() % 600)
		
		var collision_spawning = get_world_3d().direct_space_state.intersect_point(newEnemy.position)

		if not collision_spawning.collider != null:
			break

#	newEnemy.position = Vector3(randi() % 800, 15, randi() % 600)

	# later might want to use groups instead of instances
	#newEnemy.add_to_group("enemies")


func spawn_enemy():
	# Instance a new enemy scene
	var newEnemy;
	var rnd = randi() % len(enemyScenes)
	var enemyScene = enemyScenes[rnd];
	spawn_enemy_instance(enemyScene.instantiate(), 2);
		
