extends Node

@export var mob_scene: PackedScene

var score = 0
var min = 1.0
var max = 6.0
var count = 0.0
# Called when the node enters the scene tree for the first time.
func _ready():
	get_tree().call_group("Mob", "queue_free")
	$Controles._hide()
	$Controles/Up.pressed.connect(_on_pressed.bind($Controles/Up))
	$Controles/Down.pressed.connect(_on_pressed.bind($Controles/Down))
	$Controles/Left.pressed.connect(_on_pressed.bind($Controles/Left))
	$Controles/Right.pressed.connect(_on_pressed.bind($Controles/Right))

func _on_pressed(button):
	if (button.name == "Up" || Input.is_action_pressed("up")):
		kill("up")
	elif (button.name == "Down" || Input.is_action_pressed("down")):
		kill("down")
	elif (button.name == "Left" || Input.is_action_pressed("left")):
		kill("left")
	elif (button.name == "Right" || Input.is_action_pressed("right")):
		kill("right")
	else:
		print(button.name, " is undefined")

func kill(name):
	
	if $Mob == null:
		print("mob non généré")
	else :
		if $Mob/AnimatedSprite2D.get_animation() == "up" && name == "up":
			$Mob.queue_free()
			score += 1
		elif $Mob/AnimatedSprite2D.get_animation() == "down" && name == "down":
			$Mob.queue_free()
			score += 1
		elif $Mob/AnimatedSprite2D.get_animation() == "left" && name == "left":
			$Mob.queue_free()
			score += 1
		elif $Mob/AnimatedSprite2D.get_animation() == "right" && name == "right":
			$Mob.queue_free()
			score += 1
		$HUD.update_score(score)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	pass

func game_over():
	$Music.stop()
	$MobTimer.stop()
	$HUD.show_game_over(score)
	$Controles._hide()
	$DeathSound.play()
	get_tree().call_group("Mob", "queue_free")

func new_game():
	score = 0
	$Music.play()
	$StartTimer.start()
	$HUD.update_score(score)
	$Controles._show()
	get_tree().call_group("Mob", "queue_free")


func _on_mob_timer_timeout():
	# Create a new instance of the Mob scene.
	var mob = mob_scene.instantiate()
	
	# Choose a random location on Path2D.
	var mob_spawn_location = $MobPath/MobSpawn
	mob_spawn_location.progress_ratio = randf()

	# Set the mob's position to a random location.
	mob.position = mob_spawn_location.position
	
	# Choose the velocity for the mob.
	var velocity = Vector2(0.0, randf_range(min + count, max + count))
	mob.linear_velocity = velocity
	count += 10.0
	mob.lock_rotation = true
	mob.angular_velocity = 0.0
	mob.angular_damp = 0.0
	get_tree().call_group("Mob", "add_gravity")
	# Spawn the mob by adding it to the Main scene.
	add_child(mob)


func _on_start_timer_timeout():
	$MobTimer.start()
	if $MobTimer.wait_time <= 1.0:
		$MobTimer.wait_time = 1.0
	else :
		$MobTimer.wait_time -= 0.01
