#include "client/game/ClientGame.h"

#include "blitz/misc/Log.h"
#include "blitz/protocol/PacketDispatcher.h"
#include "blitz/protocol/packets/PlayerJoinPacket.h"
#include "blitz/protocol/packets/PlayerLeavePacket.h"
#include "blitz/protocol/packets/PlayerListPacket.h"
#include "blitz/protocol/packets/PlayerPositionAndRotationPacket.h"
#include "client/Client.h"

namespace blitz {
namespace client {

ClientGame::ClientGame(Client* client, protocol::PacketDispatcher* dispatcher) :
	protocol::PacketHandler(dispatcher), m_Client(client) {
	RegisterHandlers();
}

ClientGame::~ClientGame() {
	GetDispatcher()->UnregisterHandler(this);
}

void ClientGame::RegisterHandlers() {
	GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerJoin, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerLeave, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerList, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerPositionAndRotation, this);
}

void ClientGame::HandlePacket(const protocol::PlayerJoinPacket* packet) {
	AddPlayer(packet->GetPlayerID(), packet->GetPlayerName());

	// Initialize camera
	if (packet->GetPlayerID() == m_Client->GetPlayerID()) {
		m_Client->NotifyListeners(&GuiListener::OnSpectatorChange, packet->GetPlayerID());
	}
}

void ClientGame::HandlePacket(const protocol::PlayerLeavePacket* packet) {
	RemovePlayer(packet->GetPlayerID());
}

void ClientGame::HandlePacket(const protocol::PlayerListPacket* packet) {
	for (const auto& [playerID, playerInfo] : packet->GetPlayers()) {
		AddPlayer(playerID, playerInfo.name);
	}
}

void ClientGame::HandlePacket(const protocol::PlayerPositionAndRotationPacket* packet) {
	if (packet->GetPlayer() == m_Client->GetPlayerID())
		return;

	game::Player* player = GetPlayerById(packet->GetPlayer());

	if (!player)
		return;

	player->SetVelocity(packet->GetPosition() - player->GetPosition());
	player->SetYaw(packet->GetYaw());
	player->SetPitch(packet->GetPitch());
}

void ClientGame::Tick(std::uint64_t delta) {
	float deltaTime = static_cast<float>(delta) / 1000.0f;
	for (auto& [playerId, player] : GetPlayers()) {
		player.SetPosition(player.GetPosition() + player.GetVelocity() * (static_cast<float>(delta) / 100.0f));
	}
}

}  // namespace client
}  // namespace blitz
