#include "object.h"
#include "json_helper.h"

namespace maps::wiki::json2ymapsdf::tds {

Object::Object(const json::Value& jsonObject, const std::string& objectId)
    : Item(jsonObject)
{
    attributes_[ATTRIBUTE_OBJECT_ID] = objectId;
    categories_ = readCategories(jsonObject);
    std::string categoryName;
    for (const auto& category: categories_) {
        if (!categoryName.empty()) {
            categoryName += ARRAY_DELIM;
        }
        categoryName += category->name();

        for (const auto& [key, value]: category->constAttributes()) {
            attributes_.try_emplace(key, value);
        }
    }
    attributes_[tds::ATTRIBUTE_CATEGORY] = categoryName;

    for (const auto& jsonLink : getLinks(jsonObject)) {
        Link link(jsonLink, objectId);
        const std::string& master = link[ATTRIBUTE_MASTER_CATEGORY];
        const std::string& role = link[ATTRIBUTE_ROLE];
        const schema::Relation& relation = schema::relation(master, role);
        const auto res = links_[relation].insert(link);
        if (!res.second) {
            DATA_ERROR() << " Relation " << link.info() << " is duplicated";
        }
    }
}

} // namespace maps::wiki::json2ymapsdf::tds
