#include <server/Server.h>

#include <blitz/godot/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_NetworkInterface = Object::cast_to<NetworkInterface>(get_parent());
	DEV_ASSERT(m_NetworkInterface);

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

void Server::OnPlayerConnect(PeerID a_PeerId) {
	protocol::PlayerInfo playerInfo{a_PeerId, "whoami"};
	for (int i = 0; i < m_Peers.size(); i++) {
		m_NetworkInterface->SendPacket(a_PeerId, protocol::packets::PlayerJoin({m_Peers[i], "whoami"}));
	}
	m_Peers.push_back(a_PeerId);
	m_NetworkInterface->BroadcastPacket(protocol::packets::PlayerJoin({playerInfo}));
}

void Server::OnPlayerDisconnect(PeerID a_PeerId) {
	m_Peers.erase(a_PeerId);
	m_NetworkInterface->BroadcastPacket(protocol::packets::PlayerLeave({a_PeerId}));
}

}  // namespace blitz