extends PanelContainer

@onready
var play_button := $HBoxContainer/PlayButton

@onready
var pause_button := $HBoxContainer/PauseButton

@onready
var stop_button := $HBoxContainer/StopButton

@onready
var audio := $AudioStreamPlayer

@onready
var progress := $HBoxContainer/HSlider

@onready
var label := $HBoxContainer/Label

@onready
var path = '/Users/sebastian/ResilioSync/Sorterat_test/Metal Gear Solid 4 - Guns of the Patriots/2-16 Metal Gear Saga.mp3'

var songs := []

var is_changing: bool = false
var playback_position: float
var stream: AudioStream

func set_songs(new_songs) -> void:
	songs = new_songs
	
func make_request(address, func_name) -> void:
	var http_request = HTTPRequest.new()
	add_child(http_request)
	http_request.request_completed.connect(func_name)
	
	# Perform a GET request. The URL below returns JSON as of writing.
	var error = http_request.request(address)
	if error != OK:
		push_error("An error occurred in the HTTP request.")

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	play_button.pressed.connect(fetch_first_song)
	pause_button.pressed.connect(pause)
	stop_button.pressed.connect(stop)
	progress.drag_started.connect(_on_drag_started)
	progress.drag_ended.connect(_on_drag_ended)

func format_time(time: float) -> String:
	var mins: String = "%02d" % floor(time / 60)
	var sec: String = "%02d" % round(fmod(time, 60))
	return  mins + ":" + sec
	
func format_text(part: float, total: float) -> String:	
	return format_time(part) + " / " + format_time(total)

func _process(_delta):
	if audio.has_stream_playback() && !is_changing && !audio.stream_paused:
		progress.value = audio.get_playback_position()
		label.text = format_text(progress.value, stream.get_length())

signal fetched

func fetch_first_song() -> void:
	var http_request = HTTPRequest.new()
	add_child(http_request)
	#http.set_download_file("https://music.sanplex.tech/music/first")
	http_request.request_completed.connect(first_song_fetched)
	
	# Perform a GET request. The URL below returns JSON as of writing.
	var error = http_request.request("https://music.sanplex.tech/music/rand")
	if error != OK:
		push_error("An error occurred in the HTTP request.")

func first_song_fetched(result, response_code, headers, body) -> void:
	if result != HTTPRequest.RESULT_SUCCESS:
		push_error("Song couldn't be downloaded. Try a different song.")
	var sound = AudioStreamMP3.new()
	sound.data = body
	make_request("https://music.sanplex.tech/music/addQue", add_que)
	#fetched.emit()
	play(sound)
	
func add_que(result, response_code, headers, body) -> void:
	print("response_code", response_code)
	fetched.emit()

func play(song) -> void:
	if audio.stream_paused:
		audio.stream_paused = false
		audio.seek(playback_position)
		print("continue")
	elif song:
		print("play given song")
		audio.stream = song
		audio.play()
		stream = audio.stream
	else:
		if songs:
			#print(songs)
			path = songs[0]
		print(path)
		print(FileAccess.file_exists(path))
		audio.stream = load_mp3(path)
		print("play")
		audio.play()
		stream = audio.stream
	progress.max_value = round(stream.get_length())
	progress.tick_count = round(stream.get_length() / 60)
	
func pause() -> void:
	audio.stream_paused = true
	playback_position = audio.get_playback_position()
	
func stop() -> void:
	audio.stop()
	audio.stream_paused = false
	progress.value = 0

func _on_drag_started() -> void:
	is_changing = true

func _on_drag_ended(_changed) -> void:
	audio.seek(progress.value)
	playback_position = progress.value
	is_changing = false

func load_mp3(_path) -> AudioStream:
	var file = FileAccess.open(_path, FileAccess.READ)
	var sound = AudioStreamMP3.new()
	sound.data = file.get_buffer(file.get_length())
	return sound
