#include "parser.h"
#include "social_constants.h"

#include <maps/libs/common/include/exception.h>
#include <maps/libs/json/include/value.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

namespace maps::wiki::sprav_feedback {

geolib3::Point2 reversedCoordsToPoint(const std::string& str)
{
    std::vector<std::string> latlon;
    boost::split(latlon, str, boost::is_any_of(","));

    REQUIRE(latlon.size() == 2, "Point string " + str + " cannot be parsed");

    return geolib3::Point2(std::stod(latlon[1]), std::stod(latlon[0]));
}

std::vector<std::string> photoUrlsFromNode(const NYT::TNode& node)
{
    if (node.IsNull() || node.IsUndefined()) {
        return {};
    }

    std::vector<std::string> photoUrls;
    for (const NYT::TNode& photoUrlNode : node.AsList()) {
        photoUrls.push_back(photoUrlNode.AsString());
    }

    return photoUrls;
}

std::optional<std::string> optionalStringFromNode(const NYT::TNode& node)
{
    std::optional<std::string> retVal;
    if (!node.IsNull()) {
        auto value = node.AsString();
        if (!value.empty()) {
            retVal = value;
        }
    }
    return retVal;
}

uint64_t getFeedbackIdFromResponse(const std::string& responseBody)
{
    auto jsonBody = maps::json::Value::fromString(responseBody);
    ASSERT(jsonBody.isObject() && jsonBody.hasField(jf::FEEDBACK_TASK));
    auto fbTask = jsonBody[jf::FEEDBACK_TASK];
    ASSERT(fbTask.isObject() && fbTask.hasField(jf::ID));
    return boost::lexical_cast<uint64_t>(fbTask[jf::ID].as<std::string>());
}

} // namespace maps::wiki::sprav_feedback
