extends Control

var host_port = 2675
var maxplayers
var ip = "127.0.0.1"
var port = 2670
var players = {}
var playername

func _ready():
	get_tree().connect("connected_to_server", self, "_connected_ok")
	get_tree().connect("connection_failed", self, "_connected_fail")
	get_tree().connect("server_disconnected", self, "_server_disconnect")
	if OS.has_environment("USERNAME"):
		$GeneralPanel/player_name.text = OS.get_environment("USERNAME")
	else:
		var desktop_path = OS.get_system_dir(0).replace("\\", "/").split("/")
		$GeneralPanel/player_name.text = desktop_path[desktop_path.size() - 2]


func _on_singleplayer_button_up():
	var _letsgo = get_tree().change_scene("res://scenes/world/World.tscn")


func _on_JoinGameBtn_button_up():
	ip = $JoinPanel/join_ip.text
	port = $JoinPanel/join_port.value
	print("Netplay - Attempting to join game at IP ",ip," via port ",port)
	join_game()

func _on_HostGameBtn_button_up():
	var host_port = $HostPanel/host_port.value
	print("Netplay - Attempting to host game on port ",host_port,"...")
	host_game(host_port)

func host_game(port):
	playername = $GeneralPanel/player_name.text
	maxplayers = $HostPanel/playercount.value
	var host = NetworkedMultiplayerENet.new()
	var hostresult = host.create_server(port, maxplayers) # ports, maxplayers
	if (hostresult==OK):
		print("Netplay - No conflicts. Starting Server")
		get_tree().set_network_peer(host)
		print("Netplay - Hosting on port ",port,". Max players: ",maxplayers)
		print("Netplay - Are you the server ... ",get_tree().is_network_server())
		$HostPanel/HostGameBtn.disabled = 1
		$HostPanel/HostGameBtn.hint_tooltip = "Cannot start another server, Server already started."
		$JoinPanel/JoinGameBtn.disabled = 1
		$JoinPanel/JoinGameBtn.hint_tooltip = "Cannot join another server, Server already started."
		$Camera2D.position.x += 640
	else:
		print("Netplay - Cant start server")
	#Goto a lobby instance

func join_game():
	playername = $GeneralPanel/player_name.text
	var host = NetworkedMultiplayerENet.new()
	var joinresult = host.create_client(ip, port)
	if (joinresult==OK):
		get_tree().set_network_peer(host)
		print("Netplay - It worked! I should be connecting...")
	else:
		print("Netplay - I was unable to connect to the server.")

func _connected_ok():
	print("Netplay - Built-in Signal - It worked! Im connected!")

func _connected_fail():
	print("Netplay - Built-in Signal - It failed")
