extends Control

const PORT=60001
signal lobby_join

func _ready():
	# Start paused.
	# This actually breaks the buttons lol
	#get_tree().paused = true
	# You can save bandwidth by disabling server relay and peer notifications.
	#multiplayer.server_relay = false
	
	# Automatically start the server in headless mode.
	if DisplayServer.get_name() == "headless":
		# Should attempt to pull port from config file
		print("Automatically starting dedicated server.")
		_on_host_pressed.call_deferred()
	else:
		Globals.multiplayer_type|=2 # displaying

func _on_host_pressed():
	# Start as server.
	var peer = ENetMultiplayerPeer.new()
	var port = $Net/Options/port.text
	if port=="": port=PORT
	peer.create_server(port)
	if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
			OS.alert("Failed to start multiplayer server.")
			return
	Globals.multiplayer_type|=1 # hosting
	multiplayer.multiplayer_peer = peer
	start_game()

func _on_join_pressed():
	# Start as client.
	var port = $Net/Options/port.text
	if port=="": port=PORT
	var txt : String = $Net/Options/address.text
	if txt == "":
			OS.alert("Need a remote to connect to.")
			return
	var peer = ENetMultiplayerPeer.new()
	peer.create_client(txt, port)
	if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
			OS.alert("Failed to start multiplayer client.")
			return
	multiplayer.multiplayer_peer = peer
	start_game() # Can't run a headless client lol what are you trying to bot the game

func start_game():
	if !Globals.multiplayer_type&2: return # displaying
	emit_signal("lobby_join",multiplayer.get_unique_id(),$Net/pname/Name.text)
	hide()
