#include "private_area.h"

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

#include <unordered_map>

namespace maps::mrc::graph_coverage_export {

PrivateAreaIndex::PrivateAreaIndex(object::Loader& loader)
{
    object::MrcRegions regions = loader.loadAllMrcRegions();

    for (auto& region : regions) {
        if (region.type() == object::MrcRegion::Type::Residential) {
            residentialRegions_.push_back(
                geolib3::convertMercatorToGeodetic(region.geom())
            );
        }
    }

    for (size_t i = 0; i < residentialRegions_.size(); i++) {
        searcher_.insert(&residentialRegions_[i], i);
    }

    searcher_.build();
}


bool PrivateAreaIndex::isInPrivateArea(const geolib3::Polyline2& polyline,
                                       int fc) const
{
    constexpr int MIN_RESIDENTIAL_FC = 7;
    if (fc < MIN_RESIDENTIAL_FC) {
        return false;
    }
    auto searchResult = searcher_.find(polyline.boundingBox());

    for (auto itr = searchResult.first; itr != searchResult.second; ++itr)
    {
        if (geolib3::spatialRelation(itr->geometry(), polyline,
                                        geolib3::SpatialRelation::Contains))
        {
            return true;
        }
    }
    return false;
}

} // namespace maps::mrc::graph_coverage_export

