extends Node3D

@onready var menu = $UI/Menu
@onready var address_entry = $UI/Menu/MarginContainer/VBoxContainer/LineEdit

const PORT = 9999
const PLAYER = preload("res://player/player.tscn")
var peer = ENetMultiplayerPeer.new()



func _on_server_button_pressed() -> void:
	menu.hide()
	peer.create_server(PORT)
	multiplayer.multiplayer_peer = peer
	multiplayer.peer_connected.connect(add_player)
	multiplayer.peer_disconnected.connect(remove_player)	

	add_player(multiplayer.get_unique_id())
	
	upnp_setup()
	
func _on_client_button_pressed() -> void:
	menu.hide()
	peer.create_client(address_entry.text,PORT)
	multiplayer.multiplayer_peer = peer
	
func add_player(peer_id):
	var player = PLAYER.instantiate()
	player.name = str(peer_id)
	add_child(player)
	
func remove_player(peer_id):
	var player = get_node_or_null(str(peer_id))
	if player:
		player.queue_free()
		
func upnp_setup():
	var upnp = UPNP.new()
	
	var discover_result = upnp.discover()
	assert(discover_result == UPNP.UPNP_RESULT_SUCCESS, \
	  "UPNP Discover Failed! Error %s" % discover_result)
	assert(upnp.get_gateway() and upnp.get_gateway().is_valid_gateway(), \
	  "UPNP Invalid Gateway!")
	
	var map_result = upnp.add_port_mapping(PORT)
	assert(map_result == UPNP.UPNP_RESULT_SUCCESS, \
	  "UPNP Port Mapping Failed ! Error %s" % map_result)
	
	print("Success! Join Adress: %s" % upnp.query_external_address())
	
