extends Control

var ServerCreateGameMenu = preload("res://scenes/menus/ServerCreateGameMenu.tscn")
var LobbyMenu = preload("res://scenes/menus/LobbyMenu.tscn")
var DirectHostMenu = preload("res://scenes/menus/DirectHostMenu.tscn")
var DirectJoinMenu = preload("res://scenes/menus/DirectJoinMenu.tscn")

onready var games_list = get_node("menu/games")
var games = []
var selected_game = {}


func _ready():
	get_node("menu/back").connect("pressed",self,"_on_back_pressed")
	client.connect("connection_succeeded", self, "_connection_succeeded")
	client.connect("connection_failed", self, "_connection_failed")
	client.connect("server_disconnected", self, "_server_disconnected")


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


func _on_multiplayer_menu_draw():
	get_games(find_node("open").is_pressed())
	get_node("refresh_timer").start()


func _on_multiplayer_menu_hide():
	get_node("refresh_timer").stop()


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


func _on_direct_host_pressed():
	var direct_host_menu = DirectHostMenu.instance()
	get_tree().get_root().add_child(direct_host_menu)
	get_tree().get_root().get_node("main_menu").hide()


func _on_direct_join_pressed():
	var direct_join_menu = DirectJoinMenu.instance()
	get_tree().get_root().add_child(direct_join_menu)
	get_tree().get_root().get_node("main_menu").hide()


func _on_open_toggled(button_pressed):
	get_games(button_pressed)


func _on_refresh_pressed():
	if get_node("refresh_timer").is_stopped():
		get_node("refresh_timer").start()
	get_games(find_node("open").is_pressed())


func _on_refresh_timer_timeout():
	get_games(find_node("open").is_pressed())


func _server_disconnected():
	show_error_dialog(tr("SERVER_DISCONNECTED"))


func show_error_dialog(text:String):
	var dialog = get_node("error_dialog")
	dialog.set_text(text)
	dialog.popup_centered()


func get_games(only_open:bool):
	var req = game_server.http()
	req.connect_http(self,"_on_get_games")
	if only_open:
		req.get_request('client/games?open')
	else:
		req.get_request('client/games')	


func _on_get_games(result, response_code, headers, body):
	if result == OK && response_code == HTTPClient.RESPONSE_OK:
		find_node("create").set_disabled(false)
		find_node("open").set_disabled(false)
		var json = JSON.parse(body.get_string_from_utf8())
		games_list.clear()
		games = json.result
		for game in games:
			var name = game.name
			name += " ("
			name += str(game.player_count)
			name += "/4)"
			if game.bots:
				name += " [with Bots]"
			games_list.add_item(name)		
			if game.running:
				games_list.set_item_icon(games_list.get_item_count()-1, games_list.get_node("running_icon").get_button_icon())
			elif game.has('private') && game.private:
				games_list.set_item_icon(games_list.get_item_count()-1, games_list.get_node("private_icon").get_button_icon())
			else:
				games_list.set_item_icon(games_list.get_item_count()-1, games_list.get_node("open_icon").get_button_icon())
	else:
		find_node("create").set_disabled(true)
		find_node("join").set_disabled(true)
		find_node("open").set_disabled(true)
		show_error_dialog(tr("SERVER_NO_CONNECTION"))
		get_node("refresh_timer").stop()


func _on_create_pressed():
	var server_create_game_menu = ServerCreateGameMenu.instance()
	get_tree().get_root().add_child(server_create_game_menu)
	get_tree().get_root().get_node("main_menu").hide()


func _on_join_pressed():
	client.join_game(game_server.SERVER_ADDR, int(selected_game['port']))


func _connection_succeeded():
	var lobby_menu = LobbyMenu.instance()
	if selected_game && selected_game.has('name'):
		gamestate.game_name = selected_game.name
	get_tree().get_root().add_child(lobby_menu)
	get_node("refresh_timer").stop()
	hide()


func _connection_failed():
	show_error_dialog(tr("CONNECTION_FAILED"))


func _on_games_item_selected(index):
	selected_game = games[index]
	find_node("join").set_disabled(false)


func _on_games_nothing_selected():
	find_node("join").set_disabled(true)