extends MultiplayerSpawner

var host : bool
var handle : String

func _ready() -> void:
	Multiplayer.client_added.connect(_on_client_added)

func _on_host_game_button_pressed() -> void:
	%Menu.visible = false
	%Hosting.visible = true
	host = true


func _on_join_game_button_pressed() -> void:
	%Menu.visible = false
	%Joining.visible = true
	host = false


func _on_menu_back_button_pressed() -> void:
	Game.go_to_title_screen()


func _on_start_hosting_button_pressed() -> void:
	var host_name = %HostHandle.text
	if len(host_name) < 3:
		return
	handle = host_name
	Multiplayer.handle = handle
	#Validate entries
	%Hosting.visible = false
	#Set fields
	%ParticipantsText.text = "[color=FFFF00]*%s (HOST)[/color]\n" % handle
	%"Host Waiting".visible = true
	%IPLabel.text = Multiplayer.get_local_ip()
	Multiplayer.become_host()


func _on_hosting_back_button_pressed() -> void:
	%Hosting.visible = false
	%Menu.visible = true


func _on_start_game_button_pressed() -> void:
	Game.start_pawn_select.rpc(true)


func _on_waiting_back_button_pressed() -> void:
	%"Host Waiting".visible = false
	if host:
		%Hosting.visible = true
	else:
		%Joining.visible = true


func _on_join_button_pressed() -> void:
	var host_name = %JoinHandle.text
	if len(host_name) < 3:
		return
	handle = host_name
	#Check for valid game
	#If found
	%Joining.visible = false
	if await Multiplayer.join_game(handle, %IPEdit.text):
		%"Host Waiting".visible = true
		%StartButton.visible = false

func _on_joining_back_button_pressed() -> void:
	%Joining.visible = false
	%Menu.visible = true

func _on_client_added(peer_handle : String, peer_id : int) -> void:
	%ParticipantsText.text = "[color=FFFF00][b]*%s[/b][/color]\n[color=FFFFFF]*%s[/color]" % [handle, peer_handle]
	%StartButton.disabled = false

func _on_level_spawned(node: Node) -> void:
	if node is Level:
		Game.level_spawned.rpc_id(1, Multiplayer.id)
