#include "get_expression.h"
#include <maps/wikimap/mapspro/services/editor/src/configs/config.h>
#include <maps/wikimap/mapspro/services/editor/src/exception.h>

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

namespace maps {
namespace wiki {
namespace {
const std::string VIEW_SQL_FORMAT = "view-sql";
}

GetFilterExpression::GetFilterExpression(
        const Request& request)
    : controller::BaseController<GetFilterExpression>(BOOST_CURRENT_FUNCTION)
    , request_(request)
{
    result_->isSQLFormat = (request_.format == VIEW_SQL_FORMAT);
}

std::string GetFilterExpression::printRequest() const
{
    std::stringstream ss;
    ss << " id: " << request_.id
       << " token: " << request_.token;
    if (!request_.format.empty()) {
        ss << " format: " << request_.format;
    }
    return ss.str();
}

void GetFilterExpression::control()
{
    auto work = cfg()->poolCore().slaveTransaction(request_.token);
    result_->expression.reset(new filters::StoredExpression(
            filters::StoredExpression::load(*work, request_.id)));

    if (result_->isSQLFormat) {
        result_->viewSql = result_->expression->parsed().viewFilterClause(*work);
    }
}


} // namespace wiki
} // namespace maps
