#include "client/Client.h"

#include "blitz/protocol/packets/ChatPacket.h"
#include "blitz/protocol/packets/DisconnectPacket.h"
#include "client/ClientConnexion.h"
#include "client/render/WorldRenderer.h"
#include "server/Server.h"
#include <cassert>

namespace blitz {

Client::Client() : m_Server(std::make_unique<server::Server>()), m_Connexion(std::make_unique<client::ClientConnexion>(this)) {}

Client::~Client() {
	protocol::DisconnectPacket packet("Client");
	m_Connexion->SendPacket(&packet);
}

void Client::Update() {
	m_Connexion->UpdateSocket();
}

bool Client::JoinGame(const std::string& pseudo, const std::string& address, std::uint16_t port) {
	return m_Connexion->Connect(pseudo, address, port);
}

bool Client::CreateGame(std::uint16_t port, const std::string& pseudo) {
	if (!m_Server->Start(port, false))
		return false;

	if (!JoinGame(pseudo, "localhost", m_Server->GetListeningPort())) {
		m_Server->Stop();
		return false;
	}

	return true;
}

void Client::SendChatText(const std::string& text) {
	protocol::ChatPacket packet(text);
	m_Connexion->SendPacket(&packet);
}

void Client::ChatTextReceived(const protocol::ColoredText& text) {
	NotifyListeners(&ChatListener::OnTextChatReceived, text);
}

bool Client::IsConnected() {
	return m_Connexion->GetSocketStatus() == network::TCPSocket::Status::Connected;
}

}  // namespace blitz