#include "objects_query_path_parser.h"

#include <maps/libs/xml/include/xml.h>
#include <maps/libs/json/include/value.h>

#include <maps/wikimap/mapspro/services/editor/src/exception.h>

#include "common.h"
#include "json_parser.h"

namespace maps {
namespace wiki {

namespace {

const std::string STR_OBJECT_PATH = "request-objecst-query-path/objects";

} // namespace

void ObjectsQueryPathParser::parse(common::FormatType formatType, const std::string& requestBody)
{
    if (formatType == common::FormatType::XML) {
        parseXml(requestBody);
    } else {
        parseJson(requestBody);
    }
}

void ObjectsQueryPathParser::parseJson(const std::string& requestBody)
{
    const auto json = json::Value::fromString(requestBody);

    WIKI_REQUIRE(
        json.hasField(STR_ELEMENT_IDS),
        ERR_BAD_DATA,
        "No " << STR_ELEMENT_IDS << " field in request"
    );

    elementIds_ = JsonParser::objectIdVector(json[STR_ELEMENT_IDS]);
}

void ObjectsQueryPathParser::parseXml(const std::string& requestBody)
{
    const auto xml = xml3::Doc::fromString(requestBody);
    const auto objects = xml.nodes(STR_OBJECT_PATH);

    std::vector<TOid> elementIds;
    for (size_t i = 0; i < objects.size(); ++i) {
        elementIds.emplace_back(objects[i].attr<TOid>(STR_ID));
    }

    elementIds_ = std::move(elementIds);
}

const std::vector<TOid>& ObjectsQueryPathParser::elementIds() const { return elementIds_; }

} // namespace wiki
} // namespace maps
