#include "districts.h"

#include "geojson.h"

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

namespace maps::mrc::gen_targets {

std::unordered_set<EdgeId> getEdgesWithinDistricts(
    const RoadNetworkData& roadNetwork,
    const std::vector<District>& districts,
    int minRoadFc,
    int maxRoadFc)
{
    std::unordered_set<EdgeId> edgesWithinDistricts;

    for (auto& district : districts) {
        auto edges = roadNetwork.getEdgesWithinPolygon(
            district.area, minRoadFc, maxRoadFc, {});
        edgesWithinDistricts.insert(edges.begin(), edges.end());
    }
    return edgesWithinDistricts;
}


std::unordered_set<EdgeId> getEdgesFromJsonPolygons(
    const RoadNetworkData& roadNetwork,
    const std::string& geojsonPolygonsFile,
    int minRoadFc,
    int maxRoadFc)
{
    auto multiDistricts = readPolygonsFromJsonFile(geojsonPolygonsFile);
    auto districts = convertMultiDistrictToDistricts(multiDistricts);
    return getEdgesWithinDistricts(roadNetwork, districts, minRoadFc, maxRoadFc);
}

std::vector<District> convertMultiDistrictToDistricts(
    std::vector<MultiDistrict>& multiDistricts)
{
    std::vector<District> districts;

    for (auto multiDistrict : multiDistricts) {
        geolib3::MultiPolygon2& area = multiDistrict.area;

        for (size_t i = 0; i < area.polygonsNumber(); i++) {
            std::string districtName = multiDistrict.name.name;
            if (area.polygonsNumber() > 1) {
                districtName += "_" + std::to_string(i + 1);
            }
            districts.push_back(District{area.polygonAt(i),
                                         DistrictName{districtName,
                                                      multiDistrict.name.locale}});
        }
    }
    return districts;
}

} // namespace maps::mrc::gen_targets
