#include "view_object.h"
#include <maps/wikimap/mapspro/services/editor/src/srv_attrs/registry.h>
#include <maps/wikimap/mapspro/libs/dbutils/include/parser.h>

namespace maps {
namespace wiki {
namespace views {

namespace {

const std::string ID = "id";
const std::string COMMIT_ID = "commit_id";
const std::string DOMAIN_COL = "domain";
const std::string SERVICE = "service";
const std::string THE_GEOM = "the_geom";

const std::string&
extractAttrFromServiceAttrs(
    const StringMap& serviceAttrs,
    const std::string& attrName)
{
    auto it = serviceAttrs.find(attrName);
    return it == serviceAttrs.end() ? s_emptyString : it->second;
}

} // namespace col

ViewObject::ViewObject(const pqxx::row& dbtuple)
    : revisionId_(dbtuple[ID].as<TOid>(), dbtuple[COMMIT_ID].as<TCommitId>())
    , domainAttrs_(dbutils::parsePGHstore(dbtuple[DOMAIN_COL].c_str()))
    , serviceAttrs_(dbutils::parsePGHstore(dbtuple[SERVICE].c_str()))
    , geom_(dbtuple[THE_GEOM])
{
}

ViewObject::ViewObject(const ObjectPtr& revisionsObject)
    : revisionId_(revisionsObject->revision())
    , geom_(revisionsObject->geom())
{
    for (const auto& attr : revisionsObject->attributes()) {
        domainAttrs_.emplace(attr.id(), attr.value());
    }
}

ViewObject::ViewObject(
        const TRevisionId& revisionId,
        const StringMap& domainAttrs,
        const StringMap& serviceAttrs,
        const Geom& geom)
    : revisionId_(revisionId)
    , domainAttrs_(domainAttrs)
    , serviceAttrs_(serviceAttrs)
    , geom_(geom)
{

}

std::string
ViewObject::categoryId() const
{
    return categoryFromAttributes(domainAttrs_);
}

const std::string&
ViewObject::screenLabel() const
{
    return extractAttrFromServiceAttrs(
        serviceAttrs_, srv_attrs::SRV_SCREEN_LABEL);
}

const std::string&
ViewObject::renderLabel() const
{
    return extractAttrFromServiceAttrs(
        serviceAttrs_, srv_attrs::SRV_RENDER_LABEL);
}

} // namespace views
} // namespace wiki
} // namespace maps
