extends AudioStreamPlayer

signal track_started

var bpm: float
var bar_beats: float
var beat_length: float
var bar_length: float
var bpm_factor: float

var audio_delta: float

var track_time: float
var bar_time: float


func _ready() -> void:
	_play_track()


func _process(_delta: float) -> void:
	var time := get_playback_position() + AudioServer.get_time_since_last_mix()
	time -= AudioServer.get_output_latency()
	audio_delta = time - track_time
	track_time = time
	bar_time = wrapf(track_time, 0, bar_length)

	Debugger.text("bpm", bpm)
	Debugger.text("bar_beats", bar_beats)
	Debugger.text("beat_length", beat_length)
	Debugger.text("bar_length", bar_length)
	Debugger.text("bpm_factor", bpm_factor)
	Debugger.text("track_time", track_time)
	Debugger.text("bar_time", bar_time)
	Debugger.text("audio_delta", audio_delta)


func _play_track() -> void:
	play()
	_get_bpm_info()
	track_started.emit()


func _get_bpm_info() -> void:
	if stream is AudioStreamMP3:
		var steam_file := stream as AudioStreamMP3
		bpm = steam_file.bpm
		bar_beats = steam_file.bar_beats
	if stream is AudioStreamOggVorbis:
		var steam_file := stream as AudioStreamOggVorbis
		bpm = steam_file.bpm
		bar_beats = steam_file.bar_beats
	beat_length = 60 / bpm
	bar_length = beat_length * bar_beats
	bpm_factor = bpm / 100
