#include "building_searcher.h"

#include <maps/libs/geolib/include/distance.h>
#include <maps/libs/geolib/include/conversion.h>

namespace maps::wiki::guide_pedestrian {

namespace {

const double EQUAL_DISTANCE_THRESHOLD_METERES = 100;

} // unnamed namespace

BuildingSearcher::BuildingSearcher(std::vector<BuildingData> buildingsData)
    : buildingsData_(std::move(buildingsData))
{
}

std::optional<BuildingData> BuildingSearcher::search(const geolib3::Point2& paramPoint) const
{
    // todo: use #include <maps/libs/geolib/include/static_geometry_searcher.h>

    std::optional<BuildingData> retVal;
    double minDistanceMeters = 1'000'000;
    const auto mercatorRatio = geolib3::MercatorRatio::fromMercatorPoint(paramPoint);
    for (const auto& buildingData : buildingsData_) {
        double distanceMeteres = mercatorRatio.toMeters(
            geolib3::distance(buildingData.pointMerc, paramPoint));
        if (distanceMeteres < minDistanceMeters) {
            minDistanceMeters = distanceMeteres;
            retVal = buildingData;
        }
    }
    if (minDistanceMeters > EQUAL_DISTANCE_THRESHOLD_METERES) {
        retVal = std::nullopt;
    }
    return retVal;
}

} // namespace maps::wiki::guide_pedestrian
