#include "get_suggest_parser.h"

#include "json_parser.h"
#include "xml_parser.h"

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

namespace maps {
namespace wiki {

namespace {

StringMap convertMultiMapToMap(StringMultiMap&& multiMap)
{
    StringMap result;
    for (const auto& pair : multiMap) {
        auto ret = result.insert(std::move(pair));
        REQUIRE(ret.second, "Multiple keys is not allowed");
    }
    return result;
}

}

void GetSuggestParser::parse(
        common::FormatType formatType,
        const std::string& requestBody)
{
    switch (formatType) {
    case common::FormatType::XML:
        parseXml(requestBody);
        break;
    case common::FormatType::JSON:
        parseJson(requestBody);
        break;
    }
}

void GetSuggestParser::parseXml(const std::string& requestBody)
{
    if (requestBody.empty()) {
        return;
    }
    xml3::Doc doc = xml3::Doc::fromString(requestBody);
    registerNamespaces(doc);

    auto node = doc.node("//wmp:editor/wmp:request-suggest");
    attributesValues_ = convertMultiMapToMap(XmlParser::readObjectAttributes(node));
    geometry_ = XmlParser::readObjectGeometry(node);
}

void GetSuggestParser::parseJson(const std::string& requestBody)
{
    if (requestBody.empty()) {
        return;
    }
    const auto json = json::Value::fromString(requestBody);
    if (json.empty()) {
        return;
    }
    if (!json.hasField(STR_ATTRS) && !json.hasField(STR_GEOMETRY)) {
        geometry_ = Geom(createGeomFromJson(json));
        return;
    }
    attributesValues_ = convertMultiMapToMap(JsonParser::readObjectAttributes(json));
    geometry_ = JsonParser::readObjectGeometry(json);
}

} // namespace wiki
} // namespace maps
