#include "shadow_attributes.h"
#include "objects_cache.h"

namespace maps::wiki {

namespace {
const std::string SHADOW_SUFFIX = "_shadow";
const std::string USE_SHADOW_SUFFIX = "_use_shadow";

void
resetShadowAttributes(const ObjectPtr& object)
{
    for (auto& attribute : object->attributes()) {
        const auto id = attribute.id();
        if (!isShadowAttributeId(id)) {
            continue;
        }
        const auto useShadowId = useShadowAttributeId(id);
        const auto curUse = object->attributes().value(useShadowId);
        if (!curUse.empty()) {
            continue;
        }
        const auto& original = object->original();
        if (original && original->attributes().value(useShadowId).empty()) {
            continue;
        }
        object->attributes().setValue(id, attribute.def().autoValue());
    }
}

}//namespace

StringMap
clearShadowAttributes(StringMap&& attributes)
{
    for (auto& attribute : attributes) {
        if (!isShadowAttributeId(attribute.first)) {
            continue;
        }
        auto it = attributes.find(useShadowAttributeId(attribute.first));
        if (it == attributes.end() || it->second.empty()) {
            attribute.second = s_emptyString;
        }
    }
    return std::move(attributes);
}

void resetShadowAttributes(ObjectsCache& cache)
{
    auto collection =
        cache.find([] (const GeoObject* obj) { return obj->isModified(); });
    for (auto& object : collection) {
        resetShadowAttributes(object);
        if (object->original()) {
            resetShadowAttributes(object->original());
        }
    }
}

bool
isShadowAttributeId(const std::string& attributeId)
{
    return
        boost::algorithm::ends_with(attributeId, SHADOW_SUFFIX)
        && !isUseShadowAttributeId(attributeId);
}

bool
isUseShadowAttributeId(const std::string& attributeId)
{
    return boost::algorithm::ends_with(attributeId, USE_SHADOW_SUFFIX);
}

std::string
useShadowAttributeId(const std::string& attributeId)
{
    ASSERT(isShadowAttributeId(attributeId));
    return attributeId.substr(0, attributeId.find(SHADOW_SUFFIX)) + USE_SHADOW_SUFFIX;
}


} // namespace maps::wiki
