#include "client/ClientConnexion.h"

#include "blitz/misc/Format.h"
#include "blitz/misc/Log.h"
#include "blitz/protocol/packets/ChatPacket.h"
#include "blitz/protocol/packets/KeepAlivePacket.h"
#include "blitz/protocol/packets/PlayerLoginPacket.h"
#include "client/Client.h"

namespace blitz {
namespace client {

ClientConnexion::ClientConnexion(Client* client) : network::Connexion(&m_Dispatcher), m_Client(client) {
	RegisterHandlers();
}

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

bool ClientConnexion::Connect(const std::string& pseudo, const std::string& address, std::uint16_t port) {
	if (!Connexion::Connect(address, port))
		return false;

	Login(pseudo);
	return true;
}

void ClientConnexion::HandlePacket(const protocol::ChatPacket* packet) {
	utils::LOG(utils::Format("Chat : %s", protocol::ChatPacket::GetColoredTextString(packet->GetMessage()).c_str()));
	m_Client->ChatTextReceived(packet->GetMessage());
}

void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
	utils::LOG("Disconnected !");
}

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

void ClientConnexion::Login(const std::string& pseudo) {
	protocol::PlayerLoginPacket packet(pseudo);
	SendPacket(&packet);
}

}  // namespace client
}  // namespace blitz
