#include "address_searcher.h"

#include <maps/libs/geolib/include/spatial_relation.h>

namespace maps::wiki::pedestrian {

AddressSearcher::AddressSearcher(const std::vector<Address>& addresses) :
    addresses_(addresses)
{
    addressBoxes_.reserve(addresses_.size());

    for (const auto& address : addresses_) {
        addressBoxes_.emplace_back(address.positionMerc.boundingBox());
        searcher_.insert(&addressBoxes_.back(), &address);
    }

    searcher_.build();
}

std::vector<Address>
AddressSearcher::getBuildingAddresses(const Building& building) const
{
    std::vector<Address> result;

    auto inBoundingBox = searcher_.find(building.polygonMerc.boundingBox());
    for (auto it = inBoundingBox.first; it != inBoundingBox.second; ++it) {
        const Address* candidateAddress = it->value();

        bool contains = geolib3::spatialRelation(
            building.polygonMerc,
            candidateAddress->positionMerc,
            geolib3::SpatialRelation::Contains
        );

        if (contains) {
            result.push_back(*candidateAddress);
        }
    }

    return result;
}


} // namespace maps::wiki::pedestrian
