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
	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_vs_man()


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 Multiplayer.join_game(handle):
		%"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
