extends Control

@onready var name_input: LineEdit = %NameInput
@onready var ip_input: LineEdit = %IpInput
@onready var status_label: Label = %StatusLabel

func _ready() -> void:
  name_input.text = Net.local_name
  Net.connected_to_server.connect(_on_connected)
  Net.connection_failed.connect(_on_failed)

func _on_singleplayer_pressed() -> void:
  Net.local_name = name_input.text.strip_edges() if name_input.text.strip_edges() != "" else "Player"
  GameState.reset_run()
  if Net.host_singleplayer():
    GameState.change_scene(GameState.SCENE_WORLD)

func _on_host_pressed() -> void:
  Net.local_name = name_input.text.strip_edges() if name_input.text.strip_edges() != "" else "Host"
  GameState.reset_run()
  if Net.host():
    status_label.text = "Hosting on port %d" % Net.DEFAULT_PORT
    GameState.change_scene(GameState.SCENE_LOBBY)
  else:
    status_label.text = "Hosting failed."

func _on_join_pressed() -> void:
  Net.local_name = name_input.text.strip_edges() if name_input.text.strip_edges() != "" else "Client"
  var addr := ip_input.text.strip_edges()
  if addr == "":
    addr = "127.0.0.1"
  status_label.text = "Connecting to %s..." % addr
  if not Net.join(addr):
    status_label.text = "Join failed."

func _on_options_pressed() -> void:
  GameState.change_scene(GameState.SCENE_OPTIONS)

func _on_quit_pressed() -> void:
  get_tree().quit()

func _on_connected() -> void:
  status_label.text = "Connected."
  GameState.change_scene(GameState.SCENE_LOBBY)

func _on_failed() -> void:
  status_label.text = "Connection failed."
