#include "BuildingGrid.h"

#include "StateChecksum.h"

void BuildingGrid::occupy(QPoint cell, BuildingId id)
{
    m_owners[{cell.x(), cell.y()}] = id;
}

void BuildingGrid::occupy(const std::vector<QPoint>& cells, BuildingId id)
{
    for (const QPoint& cell : cells)
    {
        occupy(cell, id);
    }
}

void BuildingGrid::release(const std::vector<QPoint>& cells)
{
    for (const QPoint& cell : cells)
    {
        m_owners.erase({cell.x(), cell.y()});
    }
}

bool BuildingGrid::isOccupied(QPoint tile) const
{
    return m_owners.count({tile.x(), tile.y()}) > 0;
}

std::optional<BuildingId> BuildingGrid::findOwner(QPoint tile) const
{
    const std::map<std::pair<int, int>, BuildingId>::const_iterator it =
        m_owners.find({tile.x(), tile.y()});
    if (it == m_owners.end())
    {
        return std::nullopt;
    }
    return it->second;
}

void BuildingGrid::appendChecksum(Hasher& hasher) const
{
    // std::map iterates in sorted key order.
    hasher.append(m_owners.size());
    for (const std::pair<const std::pair<int, int>, BuildingId>& entry : m_owners)
    {
        hasher.append(entry.first.first);
        hasher.append(entry.first.second);
        hasher.append(entry.second);
    }
}
