class_name PlayerManager
extends Node

static var instance: PlayerManager

@export var player_spawner: Spawner = null
@export_file("*.tscn") var gameover_path: String = ""
@export var gameover_sound: AudioStream = null

var is_alive: bool = true
var control_enabled: bool = false
var current_speed: float = 0.0
var is_finished: bool = false
var is_stared: bool = false


static func get_instance() -> PlayerManager:
	return instance


func _init() -> void:
	if not instance:
		instance = self


func _ready() -> void:
	RideManager.get_instance().times_up.connect(game_over)


func crash() -> void:
	if is_finished:
		return
	current_speed = 0.0
	Globals.player_lives -= 1
	if Globals.player_lives >= 0:
		await get_tree().create_timer(1.0).timeout
		player_spawner.spawn()
	else:
		game_over()


func game_over() -> void:
	Music.stop()
	await get_tree().create_timer(0.5).timeout
	PulseSound1.load_and_play(gameover_sound)
	await PulseSound1.finished
	get_tree().change_scene_to_file(gameover_path)


func finish() -> void:
	control_enabled = false
	is_finished = true
	current_speed = 0.0


func start() -> void:
	control_enabled = true
	is_stared = true
