#include "utils.h"
#include <maps/libs/geolib/include/intersection.h>

namespace maps::wiki::validator {

namespace {

const std::string CAT_BOUND_JC = "cat:bound_jc";

} // namespace

std::string extractCategoryId(const revision::Attributes& revAttrs)
{
    for (const auto& attr : revAttrs) {
        if (attr.first.starts_with(validator::CAT_PREFIX)
                && attr.first != CAT_BOUND_JC) {
            return attr.first.substr(validator::CAT_PREFIX.length());
        }
    }
    return {};
}

std::vector<geolib3::BoundingBox> unionIntersectedBoundingBoxes(
    std::vector<geolib3::BoundingBox> bboxes)
{
    while (true) {
        std::vector<geolib3::BoundingBox> nonIntersected;

        // start with end of bboxes
        for (size_t i = bboxes.size(); i--;) {
            bool alone = true;
            for (size_t j = 0; j < i; ++j) {
                if (geolib3::intersects(bboxes[j], bboxes[i])) {
                    bboxes[j] = geolib3::expand(bboxes[j], bboxes[i]);
                    alone = false;
                    break;
                }
            }
            if (alone) {
                // vector has not push_front()
                // using reverse() after cycle
                nonIntersected.push_back(bboxes[i]);
            }
        }
        if (nonIntersected.size() == bboxes.size()) {
            break;
        }
        bboxes.swap(nonIntersected);

        // using reverse() to keep order
        std::reverse(bboxes.begin(), bboxes.end());
    }
    return bboxes;
}

} // namespace maps::wiki::validator
