#include "client/Client.h"
#include "td/misc/Format.h"

#include "td/protocol/packets/DisconnectPacket.h"
#include "td/protocol/packets/PlaceTowerPacket.h"
#include "td/protocol/packets/RemoveTowerPacket.h"
#include "td/protocol/packets/SelectTeamPacket.h"
#include "td/protocol/packets/UpgradeTowerPacket.h"

namespace td {
namespace client {

bool Client::Connect(const network::IPAddresses& addresses, std::uint16_t port) {
	for (const network::IPAddress& address : addresses) {
		if (address.IsValid() && m_Connexion.Connect(address.ToString(), port)) {
			m_Connected = true;
			return true;
		}
	}
	utils::LOGE("Failed to connect !");
	return false;
}

void Client::SelectTeam(game::TeamColor team) {
	if (!m_Connected)
		return;

	protocol::SelectTeamPacket packet(team);
	m_Connexion.SendPacket(&packet);
}

void Client::CloseConnection() {
	if (!m_Connected)
		return;

	m_Connected = false;

	protocol::DisconnectPacket packet;
	m_Connexion.SendPacket(&packet);

	m_Game->SetGameState(game::GameState::Disconnected);
	m_Connexion.CloseConnection();

	Reset();
}

void Client::Tick(std::uint64_t delta) {
	if (!m_Connected)
		return;
	m_Connected = m_Connexion.UpdateSocket();
	if (!m_Connected) {
		utils::LOG(utils::format("Disconnected ! (Reason : %s)", m_Connexion.GetDisconnectReason().c_str()));
		Reset();
	} else {
		m_Game->Tick(delta);
	}
}

void Client::Render() {
	m_Game->RenderWorld();
}

void Client::Reset() {
	m_Game.reset(0);
	m_Game = std::make_unique<ClientGame>(this);
}

void Client::SendMobs(const std::vector<protocol::MobSend>& mobSends) {
	protocol::SendMobsPacket packet(mobSends);
	m_Connexion.SendPacket(&packet);
}

void Client::PlaceTower(game::TowerType type, const Vec2f& position) {
	protocol::PlaceTowerPacket packet(position.x, position.y, type);
	m_Connexion.SendPacket(&packet);
}

void Client::UpgradeTower(game::TowerID tower, game::TowerLevel level) {
	protocol::UpgradeTowerPacket packet(tower, level);
	m_Connexion.SendPacket(&packet);
}

void Client::RemoveTower(game::TowerID tower) {
	protocol::RemoveTowerPacket packet(tower);
	m_Connexion.SendPacket(&packet);
}

} // namespace client
} // namespace td
