#include "objects_query_poi_business_id.h"

#include "maps/wikimap/mapspro/services/editor/src/utils.h"
#include "maps/wikimap/mapspro/services/editor/src/branch_helpers.h"
#include "maps/wikimap/mapspro/services/editor/src/views/objects_query.h"
#include "maps/wikimap/mapspro/services/editor/src/configs/config.h"

#include <yandex/maps/wiki/filters/stored_expression.h>

namespace maps {
namespace wiki {

ObjectsQueryPoiBusinessId::ObjectsQueryPoiBusinessId(const Request& request)
    : controller::BaseController<ObjectsQueryPoiBusinessId>(BOOST_CURRENT_FUNCTION)
    , request_(request)
{
}

std::string
ObjectsQueryPoiBusinessId::Request::dump() const
{
    std::stringstream ss;
    ss << " busines-id: " << businessId;
    ss << " geom: " << geomJson;
    if (distance) {
        ss << " d: " << *distance;
    }
    ss << " token: " << dbToken;
    ss << " branch: " << branchId;
    return ss.str();
}

std::string
ObjectsQueryPoiBusinessId::printRequest() const
{
    return request_.dump();
}

void
ObjectsQueryPoiBusinessId::control()
{
    WIKI_REQUIRE(!request_.businessId.empty(),
        ERR_BAD_REQUEST,
        "Non empty business-id is required.");
    auto workView = BranchContextFacade::acquireWorkReadViewOnly(
        request_.branchId, request_.dbToken);
    views::ObjectsQuery objectsQuery;
    objectsQuery.addCondition(
        views::DomainAttributeCondition(
            *workView,
            ATTR_POI_BUSINESS_ID,
            request_.businessId));
    if (!request_.geomJson.empty()) {
        WIKI_REQUIRE(
            request_.distance, ERR_BAD_REQUEST,
            "Distance is required if geometry passed.");
        Geom geom(createGeomFromJsonStr(request_.geomJson));
        WIKI_REQUIRE(
            !geom.isNull() && geom->getGeometryTypeId() == geos::geom::GEOS_POINT,
            ERR_BAD_REQUEST,
            "Point type geometry expected.");
        geom = geom.createBuffer(*request_.distance);
        objectsQuery.addCondition(views::IntersectsGeometryCondition(*workView, geom));
    }
    objectsQuery.exec(*workView, request_.branchId).swap(result_->viewObjects);
}

} // namespace wiki
} // namespace maps
