#include "junction_geom_index.h"

#include "util.h"

#include <maps/wikimap/mapspro/libs/views/include/query_builder.h>

#include <string>
#include <sstream>
#include <utility>


namespace maps {
namespace wiki {


JunctionGeomIndex::JunctionGeomIndex(
        Transaction& viewTxn,
        TBranchId branchId,
        std::string categoryId)
    : viewTxn_(viewTxn)
    , branchId_(branchId)
    , categoryId_(std::move(categoryId))
{}

TOIds JunctionGeomIndex::idsByBox(const geolib3::BoundingBox& box)
{
    std::ostringstream bbox;
    bbox.precision(DOUBLE_FORMAT_PRECISION);
    bbox <<
        "ST_SetSRID("
            "ST_MakeBox2D(" <<
                "ST_MakePoint(" << box.minX() << "," << box.minY() << "),"
                "ST_MakePoint(" << box.maxX() << "," << box.maxY() << ")"
            "),"
            "3395"
        ")";

    views::QueryBuilder qb(branchId_);
    qb.selectFields("id");
    qb.fromTable(views::TABLE_OBJECTS_P, "p");
    qb.whereClause(
        "domain_attrs ? " + viewTxn_.quote("cat:" + categoryId_) +
        " AND the_geom && " + bbox.str());

    TOIds ids;
    for (const auto& row: viewTxn_.exec(qb.query())) {
        ids.insert(row[0].as<TOid>());
    }

    return ids;
}

} // namespace wiki
} // namespace maps


