extends Control

const REFRESH_SERVER_DELAY = 5.0

export var scale := 4.0 setget set_scale
export var upThreshold := 1.0/59.0
export var downThreshold := 1.0/30.0

export var delay := 1.0
export var refresh_server_remaining := REFRESH_SERVER_DELAY

onready var viewport := $Viewport
onready var background := $Background
onready var netgame := $"/root/Multiplayer"
onready var server_list := $Popup/MarginContainer/VBoxContainer/ItemList
onready var name_field := $CenterContainer/PanelContainer/HBoxContainer/HBoxContainer/NameField

var servers := []

func _ready() -> void:
	name_field.text = netgame.player_name
	set_scale(scale)
	$"/root/Music/BGM".play()
	netgame.connect("ms_updated", self, "_ms_update")
	request_servers()

func _process(delta: float) -> void:
	refresh_server_remaining -= delta
	if refresh_server_remaining <= 0:
		request_servers()
		refresh_server_remaining = REFRESH_SERVER_DELAY
	# Give the system time to adjust
	if delay > 0:
		delay -= delta
		return
	if delta > downThreshold:
		print("GPU is taking too much (%ss > %ss), adjusting shader scale" % [ delta, downThreshold ])
		set_scale(scale+1)
	elif delta < upThreshold and scale > 2:
		print("GPU is taking it easy (%ss < %ss), adjusting shader scale" % [ delta, upThreshold ])
		set_scale(scale-1)

func request_servers():
	netgame.ms_get_entries()

const server_list_format = "{name} ({address}) - {players}/{max_players} players"
func _ms_update(action, result):
	if action == "list_games":
		# Reset server list
		server_list.clear()
		servers = result
		for server in servers:
			server.data.address = server.address
			server_list.add_item(server_list_format.format(server.data))

func set_scale(val) -> void:
	scale = val
	if viewport:
		viewport.size = rect_size / scale
		background.update()

func _on_resized() -> void:
	if viewport:
		viewport.size = rect_size / scale
		background.update()

func _host_pressed() -> void:
	$"/root/Multiplayer".host()

func _join_pressed() -> void:
	$Popup.popup_centered_ratio()

func join_server(server) -> void:
	$"/root/Music/BGM".stop()
	netgame.join(server)

func _server_addr_changed(new_text: String) -> void:
	$Popup/MarginContainer/VBoxContainer/HBoxContainer/Button.disabled = new_text.length() < 1

func _manual_join_pressed():
	join_server({ "address": $Popup/MarginContainer/VBoxContainer/HBoxContainer/LineEdit.text })

func _server_item_clicked(index):
	$"/root/Music/BGM".stop()
	join_server(servers[index])
