#include "get_filters.h"

#include <maps/wikimap/mapspro/services/editor/src/check_permissions.h>
#include <maps/wikimap/mapspro/services/editor/src/configs/config.h>

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

namespace maps {
namespace wiki {

GetFilters::GetFilters(const Request& request)
    : controller::BaseController<GetFilters>(BOOST_CURRENT_FUNCTION)
    , request_(request)
{
    result_->page = request_.page;
    result_->perPage = request_.perPage;
    result_->totalCount = 0;
}

std::string GetFilters::printRequest() const
{
    std::stringstream ss;
    ss << " uid: " << request_.uid;

    if (request_.createdBy) {
        ss << " created-by: " << *request_.createdBy;
    }

    ss << " page: " << request_.page
       << " per-page: " << request_.perPage
       << " token: " << request_.token;
    return ss.str();
}

void GetFilters::control()
{
    auto work = cfg()->poolCore().slaveTransaction(request_.token);
    CheckPermissions(request_.uid, *work).checkPermissionsToViewFilters();
    if (request_.limit) {
        auto result = filters::StoredFilter::load(
                *work,
                request_.uid,
                request_.createdBy,
                request_.namePart,
                request_.startId,
                request_.beforeAfter,
                request_.limit);
        result_->filters = std::move(result.filters);
        result_->hasMore = result.hasMore;
    } else {
        auto result = filters::StoredFilter::loadPaged(
                *work, request_.uid,
                request_.page, request_.perPage, request_.createdBy);
        result_->filters = std::move(result.value());
        result_->totalCount = result.pager().totalCount();
    }
}

} // namespace wiki
} // namespace maps
