#include "Server.h"

#include "Lobby.h"
#include "NetworkInterface.h"
#include <godot_cpp/classes/engine.hpp>

using namespace godot;

namespace blitz {

void Server::_bind_methods() {}

Server::Server() {}

Server::~Server() {}

void Server::_ready() {
	if (Engine::get_singleton()->is_editor_hint())
		return;


	m_Lobby = Object::cast_to<Lobby>(get_parent());
	DEV_ASSERT(m_Lobby);
	m_NetworkInterface = Object::cast_to<NetworkInterface>(m_Lobby->find_child("NetworkInterface"));
	DEV_ASSERT(m_NetworkInterface);

	m_Lobby->connect("player_connected", callable_mp(this, &Server::OnPlayerConnect));
	m_Lobby->connect("player_disconnected", callable_mp(this, &Server::OnPlayerDisconnect));
}

void Server::OnPlayerConnect(uint64_t a_PeerId) {
	for (int i = 0; i < m_Peers.size(); i++) {
		m_NetworkInterface->rpc_id(a_PeerId, "AddPlayer", m_Peers[i], "Aucuneidee");
	}
	m_Peers.push_back(a_PeerId);
	m_NetworkInterface->rpc("AddPlayer", a_PeerId, "Aucuneidee");
}

void Server::OnPlayerDisconnect(uint64_t a_PeerId) {
	m_Peers.erase(a_PeerId);
	m_NetworkInterface->rpc("RemovePlayer", a_PeerId);
}

}  // namespace blitz