#include "game/client/Client.h"

#include <iostream>

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;
        }
    }
    std::cout << "Failed to connect !\n";
    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);
}

void Client::tick(std::uint64_t delta) {
    if (!m_Connected)
        return;
    m_Connected = m_Connexion.updateSocket();
    if (!m_Connected) {
        std::cout << "Disconnected ! (Reason : " << m_Connexion.getDisconnectReason() << ")\n";
    } else {
        m_Game.tick(delta);
    }
}

void Client::render() {
    m_Game.renderWorld();
}

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

void Client::placeTower(game::TowerType type, const glm::vec2& 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);
}

} // namespace client
} // namespace td
