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

namespace td {
namespace client {

ClientConnexion::ClientConnexion() : Connexion(&m_Dispatcher) {
    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_Ping = utils::getTime() - packet->getPacketSendTime();
}

void ClientConnexion::login() {
    td::protocol::PlayerLoginPacket loginPacket("Persson" + std::to_string(m_ConnectionID));
    sendPacket(&loginPacket);
}

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

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

} // namespace client
} // namespace td
