extends Control


func _ready():
	var player_name = local_storage.read_value("player_name", false)
	var game_title = "New Game"
	if player_name:
		game_title += " by " + player_name
	find_node("name").set_text(game_title)
	find_node("bots").set_pressed(local_storage.read_value("bots", true))


func _draw():
	find_node("create").grab_focus()


func _on_create_pressed():
	var req = game_server.http()
	req.connect_http(self,"_on_game_created")
	var server_name = find_node("name").text
	var bots = 0
	if find_node("bots").is_pressed():
		bots = 1
	req.post_request('client/game/create', to_json({'name' : server_name, 'bots' : bots}))	


func _on_game_created(result, response_code, headers, body):
	if result == OK && response_code == HTTPClient.RESPONSE_OK:
		var json = JSON.parse(body.get_string_from_utf8())
		gamestate.game_name = json.result['name']
		client.join_game(game_server.SERVER_ADDR, int(json.result['port']))
	queue_free()


func _on_name_text_changed(new_text):
	if new_text:
		find_node("create").set_disabled(false)
	else:
		find_node("create").set_disabled(true)


func _on_back_pressed():
	queue_free()
	get_tree().get_root().get_node("multiplayer_menu").show()
