extends CanvasLayer

@export var address = "127.0.0.1"
@export var port = 8910
@export var player_name: LineEdit
@export var map_root: Node
@export var host_button: Button
@export var join_button: Button
@export var address_input: LineEdit
@export var playerList: ItemList
@export var start_button: Button


var peer

# Called when the node enters the scene tree for the first time.
func _ready():
	multiplayer.peer_connected.connect(peer_connected)
	multiplayer.peer_disconnected.connect(peer_disconnected)
	multiplayer.connected_to_server.connect(connected_to_server)
	multiplayer.connection_failed.connect(connection_failed)
	join_button.button_up.connect(_on_join_button_down)
	host_button.button_up.connect(_on_host_button_down)
	start_button.button_up.connect(_on_start_button_down)
	start_button.disabled = true

### Server and Client
func peer_connected(id):
	print("Peer connected: ", id);

### Server and Client
func peer_disconnected(id):
	print("Peer disconnected: ", id)
	if id == 1:
		print("Server Disconnected !!!!!")
		var tree = get_children()
		print("Children: ", tree)
		for child in map_root.get_children():
			child.queue_free()
		GameManager.players.clear()
		$Lobby.hide()
		$MainMenu.show()
		self.show()
	GameManager.players.erase(id)
	playerList.clear()
	for i in GameManager.players:
		playerList.add_item(GameManager.players[i].name, null, false)
	var players = get_tree().get_nodes_in_group("Player")
	for i in players:
		if i.name == str(id):
			i.queue_free()
			break

### Client
func connected_to_server():
	print("Connected to server :)")
	SendPlayerInformation.rpc_id(1, player_name.text, multiplayer.get_unique_id())
	#SendPlayerInformation(nick, multiplayer.get_unique_id())

### Client
func connection_failed():
	print("Disconnected from server :(")

@rpc("any_peer")
func SendPlayerInformation(nickname, id):
	var me = multiplayer.get_unique_id()
	var sender_id = multiplayer.get_remote_sender_id()
	print(me, ": got info on ", id, " from ", sender_id)
	if !GameManager.players.has(id):
		GameManager.players[id] ={
			"name" : nickname,
			"id" : id,
			"score": 0
		}
		playerList.add_item(str(nickname), null, false)
	if multiplayer.is_server():
		print(me, ": Is Server!")
		for i in GameManager.players:
			print(me, ": Sending(?) player ", i)
			SendPlayerInformation.rpc(GameManager.players[i].name, i)

@rpc("any_peer","call_local")
func StartGame():
	var me = multiplayer.get_unique_id()
	print(me, ": Starting Game\n", me, ": Players: ", GameManager.players)
	var scene = load("res://test_map.tscn").instantiate()
	#get_tree().root.add_child(scene)
	map_root.add_child(scene)
	self.hide()


func _on_host_button_down():
	peer = ENetMultiplayerPeer.new()
	var error = peer.create_server(port, 2)
	if error != OK:
		print("cannot host: " + error)
		return
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)
	multiplayer.set_multiplayer_peer(peer)
	print("Waiting For Players!")
	SendPlayerInformation(player_name.text, multiplayer.get_unique_id())
	$MainMenu.hide()
	$Lobby.show()
	start_button.disabled = false
	#SendPlayerInformation(nick, multiplayer.get_unique_id())

func _on_join_button_down():
	peer = ENetMultiplayerPeer.new()
	peer.create_client(address, port)
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)
	multiplayer.set_multiplayer_peer(peer)
	$MainMenu.hide()
	$Lobby.show()


func _on_start_button_down():
	StartGame.rpc()
