#include "game/client/WorldClient.h"
#include "protocol/PacketDispatcher.h"
#include "game/client/ClientGame.h"
#include "render/WorldRenderer.h"

namespace td {
namespace client {

WorldClient::WorldClient(ClientGame* game) : game::World(game), protocol::PacketHandler(game->GetDispatcher()), m_Game(game) {
    GetDispatcher()->RegisterHandler(protocol::PacketType::WorldAddTower, this);
    GetDispatcher()->RegisterHandler(protocol::PacketType::WorldBeginData, this);
    GetDispatcher()->RegisterHandler(protocol::PacketType::WorldData, this);
    GetDispatcher()->RegisterHandler(protocol::PacketType::SpawnMob, this);
    GetDispatcher()->RegisterHandler(protocol::PacketType::UpgradeTower, this);
}

void WorldClient::HandlePacket(const protocol::WorldBeginDataPacket* packet) {
    loadMap(packet);
}

void WorldClient::HandlePacket(const protocol::WorldDataPacket* packet) {
    loadMap(packet);
}

void WorldClient::HandlePacket(const protocol::SpawnMobPacket* packet) {
    spawnMobAt(packet->getMobID(), packet->getMobType(), packet->getMobLevel(), packet->getSender(),
        packet->getMobX(), packet->getMobY(), packet->getMobDirection());
}

void WorldClient::HandlePacket(const protocol::UpgradeTowerPacket* packet) {
    game::TowerPtr tower = getTowerById(packet->getTowerID());
    if (tower == nullptr) return; // this should not happen but who knows ?
    tower->upgrade(packet->getTowerLevel().getLevel(), packet->getTowerLevel().getPath());
}

void WorldClient::HandlePacket(const protocol::WorldAddTowerPacket* packet) {
    game::TowerPtr newTower = placeTowerAt(packet->getTowerID(), packet->getTowerType(), packet->getTowerX(), packet->getTowerY(), packet->getBuilder());

    notifyListeners(&WorldListener::OnTowerAdd, newTower);
}

} // namespace client
} // namespace td
