extends Node


const SERVER_PORT = 8080
const SERVER_IP = "127.0.0.1"
var handle : String
var id : int
var players : Dictionary = {}
signal client_added(handle : String, id : int)

func become_host() -> void:
	print("Starting host!")
	
	var server_peer = ENetMultiplayerPeer.new()
	server_peer.create_server(SERVER_PORT)
	players[handle] = 1
	multiplayer.multiplayer_peer = server_peer
	id = multiplayer.get_unique_id()
	print("%s %d t" % [handle, multiplayer.get_unique_id()])
	multiplayer.peer_connected.connect(_add_player_to_game)
	multiplayer.peer_disconnected.connect(_remove_player_from_game)


func join_game(new_handle : String) -> Error:
	print("Player 2 joining.")
	
	var client_peer = ENetMultiplayerPeer.new()
	var error = client_peer.create_client(SERVER_IP, SERVER_PORT)
	multiplayer.multiplayer_peer = client_peer
	handle = new_handle
	id = multiplayer.get_unique_id()
	if !error:
		print("%s %d" % [handle, multiplayer.get_unique_id()])
	return !error



func _add_player_to_game(id : int) -> void:
	print("Player %s joined the game!" % id)
	await get_tree().create_timer(0.5).timeout
	get_handle_from_peer(id)

func _remove_player_from_game(id : int) -> void:
	print("Player %s left the game!" % id)

func get_handle_from_peer(peer_id) -> void:
	rpc_id(peer_id, "report_handle_to_peer", id)

@rpc("any_peer", "call_remote")
func receive_peer_handle(peer_id, peer_handle) -> void:
	print("Player %s identified as %s!" % [peer_id, peer_handle])
	players[peer_handle] = peer_id
	client_added.emit(peer_handle, peer_id)

@rpc("any_peer", "call_remote")
func report_handle_to_peer(peer_id : int) -> void:
	rpc_id(peer_id, "receive_peer_handle", multiplayer.get_unique_id(), handle)
