#include "client/ClientConnexion.h"
#include "client/render/WorldRenderer.h"

#include "td/protocol/packets/ConnectionInfoPacket.h"
#include "td/protocol/packets/DisconnectPacket.h"
#include "td/protocol/packets/KeepAlivePacket.h"
#include "td/protocol/packets/PlayerLoginPacket.h"
#include "td/protocol/packets/ServerTpsPacket.h"

#include "td/misc/Random.h"

namespace td {
namespace client {

ClientConnexion::ClientConnexion() : Connexion(&m_Dispatcher), m_ServerTPS(0) {
	RegisterHandlers();
}

void ClientConnexion::RegisterHandlers() {
	GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::ConnectionInfo, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this);
	GetDispatcher()->RegisterHandler(protocol::PacketType::ServerTps, this);
}

void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
	protocol::KeepAlivePacket keepAlivePacket(packet->GetAliveID());
	SendPacket(&keepAlivePacket);
}

void ClientConnexion::HandlePacket(const protocol::ConnexionInfoPacket* packet) {
	m_ConnectionID = packet->GetConnectionID();
	Login();
}

void ClientConnexion::HandlePacket(const protocol::ServerTpsPacket* packet) {
	m_ServerTPS = packet->GetTPS();
	m_ServerMSPT = packet->GetMSPT();
	m_Ping = utils::GetTime() - packet->GetPacketSendTime();
}

void ClientConnexion::Login() {
	td::protocol::PlayerLoginPacket loginPacket("Persson#" + std::to_string(utils::GetRandomInt(0, 9999)));
	SendPacket(&loginPacket);
}

bool ClientConnexion::UpdateSocket() {
	return Connexion::UpdateSocket();
}

void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
	m_DisconnectReason = packet->GetReason();
	CloseConnection();
}

} // namespace client
} // namespace td
