## freeftf
## Copyright (C) 2024  Patrick_Pluto
##
## This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.

extends Node

const PORT = 35000
const MAX_CONNECTIONS = 256

var game_rooms = {}
var player_associations = {}
var name_associations = {}


func _ready():
	multiplayer.peer_disconnected.connect(_on_player_disconnected)
	multiplayer.peer_connected.connect(_on_player_connected)

func create_game():
	var peer = ENetMultiplayerPeer.new()
	var error = peer.create_server(PORT, MAX_CONNECTIONS)
	if error:
		return error
	multiplayer.multiplayer_peer = peer

func _on_player_disconnected(id):
	while multiplayer.is_server():
		for i in range(5000):
			if id in multiplayer.get_peers():
				break
			await get_tree().create_timer(0.001).timeout
		var room_name = player_associations[id]
		var player_list = create_player_list(room_name)
		if game_rooms.has(room_name) and game_rooms[room_name] == id:
			for p in player_list:
				Client.rpc_id(p,"room_closed")
			game_rooms.erase(room_name)
		else:
			for p in player_list:
				Client.rpc_id(p,"_on_player_disconnected",id)
		player_associations.erase(id)
		name_associations.erase(id)
		break
	
func _on_player_connected(id):
	if multiplayer.is_server():
		Client.rpc_id(id,"send_playerinfo")

func create_player_list(room_name):
	var player_list = {}
	for player in player_associations:
		if player_associations[player] == room_name:
			player_list[player] = name_associations[player]
	return player_list

@rpc("any_peer","call_remote","reliable")
func recieve_playerinfo(player_name, room_name):
	var exists = false
	var id = multiplayer.get_remote_sender_id()
	for game_room in game_rooms:
		if game_room == room_name:
			exists = true
	player_associations[id] = room_name
	name_associations[id] = player_name
	if !exists:
		game_rooms[room_name] = id
		Server.rpc_id(id,"elevate")
	var player_list = create_player_list(room_name)
	for p in player_list:
		Client.rpc_id(p,"get_player_list",player_list)