#include "objects_query_category.h"

#include "maps/wikimap/mapspro/services/editor/src/branch_helpers.h"
#include "maps/wikimap/mapspro/services/editor/src/objects_cache.h"
#include "maps/wikimap/mapspro/services/editor/src/configs/config.h"
#include "maps/wikimap/mapspro/services/editor/src/revisions_facade.h"

#include <yandex/maps/wiki/configs/editor/categories.h>

namespace maps {
namespace wiki {
namespace rf = revision::filters;

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

ObjectsQueryCategory::~ObjectsQueryCategory() {}

std::string
ObjectsQueryCategory::printRequest() const
{
    std::stringstream ss;
    ss << " categoryId: " << request_.categoryId;
    ss << " user: " << request_.uid;
    ss << " token: " << request_.dbToken;
    ss << " branch: " << request_.branchId;
    return ss.str();
}

void
ObjectsQueryCategory::control()
{
    ASSERT(cfg()->editor()->categories().defined(request_.categoryId));
    const auto& category = cfg()->editor()->categories()[request_.categoryId];
    ASSERT(category.suggest());
    const CachePolicy policy {
        TableAttributesLoadPolicy::Load,
        ServiceAttributesLoadPolicy::Load,
        DanglingRelationsPolicy::Ignore
    };
    result_->cache.reset(
        new ObjectsCache(
            BranchContextFacade::acquireRead(request_.branchId, request_.dbToken),
            boost::none,
            policy
        )
    );
    auto& cache = *result_->cache;
    TOIds oids;
    const auto canonicalCategoryId = plainCategoryIdToCanonical(category.id());
    auto idRows = cache.workView().exec(
        "SELECT DISTINCT object_id FROM suggest_data WHERE categories ? '" +
        canonicalCategoryId + "';");
    for (const auto& idRow : idRows) {
        oids.insert(idRow[0].as<TOid>());
    }
    for (auto& object: cache.get(oids)) {
        result_->collection.add(std::move(object));
    }
}

} // namespace wiki
} // namespace maps
