extends Node3D

var _local_role: String = ""
var _pending_player_name: String = ""


func _ready() -> void:
	$CanvasLayer/JoinPanel/RoleOption.add_item("Spieler")
	$CanvasLayer/JoinPanel/RoleOption.add_item("DM")

	$CanvasLayer/JoinPanel/JoinButton.pressed.connect(_on_join_pressed)
	$CanvasLayer/WaitPanel/StartButton.pressed.connect(_on_start_pressed)

	NetworkManager.connected_to_server.connect(_on_connected)
	NetworkManager.connection_failed.connect(_on_connection_failed)
	NetworkManager.player_joined.connect(_on_player_joined)
	NetworkManager.player_left.connect(_on_player_left)
	NetworkManager.player_list_synced.connect(_rebuild_player_list)


func _on_join_pressed() -> void:
	var player_name: String = ($CanvasLayer/JoinPanel/NameInput as LineEdit).text.strip_edges()
	if player_name.is_empty():
		return
	_local_role = "dm" if $CanvasLayer/JoinPanel/RoleOption.selected == 1 else "player"
	_pending_player_name = player_name
	NetworkManager.join_server("127.0.0.1", 4242)


func _on_connected() -> void:
	NetworkManager.register.rpc_id(1, _pending_player_name, _local_role)
	$CanvasLayer/JoinPanel.visible = false
	$CanvasLayer/WaitPanel.visible = true
	$CanvasLayer/WaitPanel/StartButton.visible = (_local_role == "dm")


func _exit_tree() -> void:
	NetworkManager.connected_to_server.disconnect(_on_connected)
	NetworkManager.connection_failed.disconnect(_on_connection_failed)
	NetworkManager.player_joined.disconnect(_on_player_joined)
	NetworkManager.player_left.disconnect(_on_player_left)
	NetworkManager.player_list_synced.disconnect(_rebuild_player_list)


func _on_connection_failed() -> void:
	push_error("[Tavern] Verbindung fehlgeschlagen")
	_local_role = ""
	_pending_player_name = ""
	$CanvasLayer/JoinPanel.visible = true
	$CanvasLayer/WaitPanel.visible = false


func _on_player_joined(_peer_id: int, _player_name: String, _role: String) -> void:
	_rebuild_player_list()


func _on_player_left(_peer_id: int) -> void:
	_rebuild_player_list()


func _rebuild_player_list() -> void:
	$CanvasLayer/WaitPanel/PlayerList.clear()
	for p in NetworkManager.players.values():
		$CanvasLayer/WaitPanel/PlayerList.add_item("%s (%s)" % [p.name, p.role])


func _on_start_pressed() -> void:
	NetworkManager.request_start_game.rpc_id(1)
