extends Control

@onready var player_list: ItemList = %PlayerList
@onready var status_label: Label = %StatusLabel
@onready var start_button: Button = %StartButton

func _ready() -> void:
  Net.peer_connected.connect(_refresh)
  Net.peer_disconnected.connect(_refresh)
  Net.server_disconnected.connect(_on_disconnect)
  start_button.visible = Net.is_host()
  if Net.is_host():
    status_label.text = "Hosting on port %d — press Start when ready" % Net.DEFAULT_PORT
  else:
    status_label.text = "Joined — waiting for host to start"
  _refresh(0)

func _refresh(_id: int) -> void:
  player_list.clear()
  var ids: Array = []
  if multiplayer.multiplayer_peer == null:
    ids.append(1)
  else:
    ids.append(multiplayer.get_unique_id())
    for p in multiplayer.get_peers():
      if not p in ids:
        ids.append(p)
  ids.sort()
  for id in ids:
    var n: String = Net.player_names.get(id, "Player %d" % id)
    player_list.add_item("[%d] %s" % [id, n])

func _on_start_pressed() -> void:
  if not Net.is_host():
    return
  _start_world.rpc()

@rpc("authority", "call_local", "reliable")
func _start_world() -> void:
  GameState.change_scene(GameState.SCENE_WORLD)

var _leaving: bool = false

func _on_back_pressed() -> void:
  if _leaving:
    return
  _leaving = true
  Net.disconnect_net()
  GameState.change_scene(GameState.SCENE_MAIN_MENU)

func _on_disconnect() -> void:
  if _leaving:
    return
  _leaving = true
  GameState.change_scene(GameState.SCENE_MAIN_MENU)
