extends Node3D

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

const port = 9999
const player_scene = 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())

	if not disable_upnp.button_pressed:
		upnp_setup()

func _on_client_button_pressed() -> void:
	var address = "localhost"
	if not disable_upnp.button_pressed:
		address = address_entry.text
	menu.hide()
	peer.create_client(address, port)
	multiplayer.multiplayer_peer = peer

func add_player(peer_id):
	var player = player_scene.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()

	if upnp.discover() != UPNP.UPNP_RESULT_SUCCESS:
		return false

	var gateway = upnp.get_gateway()
	if not gateway.is_valid_gateway():
		return false

	if upnp.add_port_mapping(port) != UPNP.UPNP_RESULT_SUCCESS:
		return false

	print("Address: " + upnp.query_external_address())
	return true
