#include <MachineComponent/AttributionComponent/AttributionComponent.hpp>
#include <MachineComponent/MachineComponent.hpp>
#include <Utilities/Utilities.hpp>
#include <World/LocalWorld/LocalWorld.hpp>

std::string AttributionComponent::tagName = "main:attributionComponent";

AttributionComponent::AttributionComponent(Machine &machine) : MachineComponent(machine) {}

void AttributionComponent::attribute(const std::string &action, Player &player)
{
    attribTable.emplace(action, player.getName());
}

void AttributionComponent::serializeState(std::vector<uint8_t> &outBytes)
{
    serializeInto(outBytes, attribTable);
}

void AttributionComponent::deserializeState(const uint8_t *bytes, size_t size)
{
    deserialize(bytes, size, attribTable);
}

void AttributionComponent::grantAchievementFor(const std::string &action, const std::string &milestoneId, int achievementId)
{
    auto it = attribTable.find(action);
    if (it == attribTable.end())
    {
        return;
    }

    const std::string &playerName = it->second;
    auto player = machine.getWorld().getPlayer(playerName);

    if (player == nullptr)
    {
        return;
    }

    player->achieve(milestoneId, achievementId);
}