class_name RideManager
extends Node

signal distance_changed(pixels: int)
signal level_distance_complited
signal level_finished
signal times_up

static var instance: RideManager

@export var finish_offset: int = 0

var current_distance: int = 0
var current_time: float = 0.0:
	set(value):
		current_time = clampf(value, 0.0, 599.9)

var _player: PlayerManager = null
var _raw_distance: float = 0.0
var _prev_rounded_distance: int = 0
var _is_distance_completed: bool = false
var _current_track: Globals.Track = null


static func get_instance() -> RideManager:
	return instance


func _init() -> void:
	instance = self


func _ready() -> void:
	_player = PlayerManager.get_instance()
	_current_track = Globals.get_current_track()
	current_time = _current_track.time


func _physics_process(delta: float) -> void:
	if not _player.is_alive or _player.is_finished:
		return
	_raw_distance += _player.current_speed * delta
	var rounded: int = round(_raw_distance)
	var pixels: int = rounded - _prev_rounded_distance
	if pixels != 0:
		distance_changed.emit(pixels)
		_prev_rounded_distance = rounded
		if _player.is_stared:
			current_distance += pixels
			current_time -= delta
			Globals.total_time += delta
		if current_time <= 0.0:
			times_up.emit()
		if (
				current_distance >= _current_track.distance - finish_offset
				and not _is_distance_completed
		):
			_is_distance_completed = true
			level_distance_complited.emit()
		if current_distance >= _current_track.distance and not _player.is_finished:
			level_finished.emit()
