#include <client/ClientWorld.h>

#include <blitz/godot/NetworkInterface.h>
#include <client/Player.h>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/multiplayer_api.hpp>

#include <godot_cpp/variant/utility_functions.hpp>

namespace blitz {

using namespace godot;

void ClientWorld::_bind_methods() {}

ClientWorld::ClientWorld() {}

ClientWorld::~ClientWorld() {}

void ClientWorld::_process(float delta) {
#if DEBUG_ENABLED
	if (Engine::get_singleton()->is_editor_hint())
		return;
#endif

	m_PassedTime += delta;
	if (m_PassedTime < 0.05f)
		return;

	m_PassedTime = 0.0f;

	UpdatePlayerPos();
}

void ClientWorld::UpdatePlayerPos() {
	Player* player = GetPlayerById(get_multiplayer()->get_unique_id());
	if (player) {
		m_NetworkInterface->BroadcastPacket(protocol::packets::PlayerPositionAndRotation(
			{get_multiplayer()->get_unique_id(), player->get_position(), player->GetCameraRotation(), player->get_velocity()}));
	}
}

void ClientWorld::HandlePacket(const protocol::packets::PlayerPositionAndRotation& a_PlayerPos) {
	const auto& data = a_PlayerPos.m_Data;
	if (data.m_Player == get_multiplayer()->get_unique_id()) {
		Player* player = GetPlayerById(get_multiplayer()->get_unique_id());
		if (player && (a_PlayerPos.m_Data.m_Position - player->get_position()).length() > 10) {
			SetPlayerPositionAndRotation(data.m_Player, data.m_Position, data.m_Rotation, data.m_Velocity);
			godot::UtilityFunctions::print("Teleported to : ", data.m_Position);
		}
		return;
	}

	SetPlayerPositionAndRotation(data.m_Player, data.m_Position, data.m_Rotation, data.m_Velocity);
}

}  // namespace blitz