#include "task_area.h"

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

namespace maps::mrc::gen_targets {

void correctTaskArea(std::pair<District, Path>& task,
                     const RoadNetworkData& roadNetwork)
{
    geolib3::PointsVector taskPoints;

    for (auto& pathEdge : task.second) {
        if (!pathEdge.isUsefulAsTarget) {
            continue;
        }
        const Edge& edge = roadNetwork.edge(pathEdge.edgeId);
        taskPoints.push_back(edge.geom.points()[0]);
        taskPoints.push_back(edge.geom.points().back());
    }
    if (taskPoints.size() > 5) {
        task.first.area = geolib3::convexHull(taskPoints);
    } else {
        // if there are just a few points, create a small bbox around them
        auto bbox = geolib3::boundingBox(taskPoints);
        bbox = geolib3::BoundingBox(
            fastGeoShift(bbox.lowerCorner(), geolib3::Vector2(-1, -1)),
            fastGeoShift(bbox.upperCorner(), geolib3::Vector2(1, 1)));

        task.first.area = bbox.polygon();
    }
}

} // namespace maps::mrc::gen_targets
