extends Node


const PORT : int = 9374
const Arena = preload("res://Scenes/Arena.tscn")
const Lobby = preload("res://Scenes/Lobby.tscn")
var console_output : TextEdit = null
var peer : NetworkedMultiplayerENet = null
var display_name : String = ""
var player_color : Color = Color.white
var name_dict = {}
var color_dict = {}

func _ready() -> void:
	randomize()
	get_tree().connect("connected_to_server", self, "_connected_to_server")
	get_tree().connect("server_disconnected", self, "_server_disconnected")
	get_tree().connect("connection_failed", self, "_connection_failed")
	$Lobby/StartButton.connect("pressed", self, "_on_StartButton_pressed")
	console_output = $ConsoleOutput

func _process(delta : float) -> void:
	if Input.is_action_just_pressed("toggle_console"):
		self.toggle_console()

func _connected_to_server() -> void:
	self.console_print("Connected to server") # Let the server know all about us (eg name)
	rpc("set_display_name", peer.get_unique_id(), display_name)
	rpc("set_player_color", peer.get_unique_id(), player_color)

func _server_disconnected() -> void:
	var button : Button = $Lobby/StartButton
	if button:
		button.disabled = false
	else:
		self.console_print("Tried to re-enable start button, but the start button could not be found")
	self.console_print("Disconnected from server") # Kick us out the game and bring back the lobby (if applicable)

func _connection_failed() -> void:
	var button : Button = $Lobby/StartButton
	button.disabled = false
	self.console_print("Connection Error")

func console_print(text : String) -> void:
	console_output.text += "\n" + text
	console_output.cursor_set_line(console_output.get_line_count())
	print(text)

func toggle_console() -> bool:
	console_output.visible = !console_output.visible
	return console_output.visible

func _on_StartButton_pressed() -> void:
	var button : Button = $Lobby/StartButton
	var ip_addr : String = $Lobby/IPLineEdit.text
	display_name = $Lobby/NameLineEdit.text
	player_color = $Lobby/ColorPicker.color
	button.disabled = true
	peer = NetworkedMultiplayerENet.new()
	peer.create_client(ip_addr, PORT)
	get_tree().set_network_peer(peer)

func arena_ready() -> void:
	rpc_id(1, 'client_ready', peer.get_unique_id())

remote func start_game() -> void:
	$Lobby.queue_free()
	var arena = Arena.instance()
	add_child(arena)
	arena.init()
	console_print('Starting Game...')
	$AudioStreamPlayer.switch_theme("combat")

remote func add_name_to_dict(id : int, display_name : String):
	name_dict[id] = display_name

remote func add_color_to_dict(id : int, color : Color):
	color_dict[id] = color

func switch_to_lobby():
	$Arena.queue_free()
	var lobby = Lobby.instance()
	add_child(lobby)
	$Lobby/StartButton.connect("pressed", self, "_on_StartButton_pressed")
	console_print('Switching back to Lobby...')
	peer.close_connection()
	$AudioStreamPlayer.switch_theme("main")

func exit_button_pressed():
	rpc_id(1, "request_exit")

remote func exit_requested():
	switch_to_lobby()




