#include "save_expression.h"
#include "magic_strings.h"

#include <maps/wikimap/mapspro/services/editor/src/check_permissions.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/exception.h>

namespace maps {
namespace wiki {

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

std::string
SaveExpression::printRequest() const
{
    std::stringstream ss;
    ss << " uid: " << request_.uid
       << " expression: '" << request_.expression << "'";
    return ss.str();
}

void
SaveExpression::control()
{
    auto work = cfg()->poolCore().masterWriteableTransaction();
    CheckPermissions(request_.uid, *work).checkPermissionsToEditFilters();
    try {
        result_->expression.reset(new filters::StoredExpression(
                filters::StoredExpression::create(
                        *work, request_.uid, request_.expression)));
    } catch (const filters::ParseError& ex) {
        THROW_WIKI_LOGIC_ERROR(
                ERR_PARSE_ERROR, "could not parse expression: " << ex.what());
    }

    result_->token = pgpool3::generateToken(*work);
    work->commit();
}

} // namespace wiki
} // namespace maps
