extends Control

@onready
var search_list := $ScrollContainer/VBoxContainer

@onready
var clear_button := $ClearButton

@onready
var close_button := $CloseButton

@onready
var search_bar := $Searchbar

var games := []

# Called when the node enters the scene tree for the first time.
func _ready():
	get_list_of_games()
	clear_button.pressed.connect(clear)
	close_button.pressed.connect(close)
	search_bar.grab_focus()
	search_bar.text_changed.connect(search)

func close():
	clear()
	self.visible = false

func search():
	print(search_bar.text)
	delete_children(search_list)
	for game in games:
		if search_bar.text == "" || game.replace(" ", "").to_lower().contains(search_bar.text.replace(" ", "").to_lower()):
			var label := Label.new()
			label.text = game
			label.autowrap_mode = TextServer.AUTOWRAP_WORD
			search_list.add_child(label)
	
static func delete_children(node):
	for n in node.get_children():
		node.remove_child(n)
		n.queue_free()

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

# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
	var json = JSON.new()
	var error = json.parse(body.get_string_from_utf8())
	
	if error == OK:
		var data_received = json.get_data()
		if typeof(data_received) == TYPE_ARRAY:
			games.append_array(data_received)
			for game in games:
				var label := Label.new()
				label.text = game
				label.autowrap_mode = TextServer.AUTOWRAP_WORD
				search_list.add_child(label)
		else:
			print("Unexpected data")

func clear():
	search_bar.text = ""
	search_bar.grab_focus()
