#include "config.h"
#include "globals.h"
#include "parsed_entity.h"

#include <dict/dictutil/str.h>

void TRTYFastArchiveParser::Parse(TParsingContext& context) const {
    const auto* config = context.Result.GetConfig().ComponentsConfig.Get<TRTYFastArchiveConfig>(FASTARCHIVE_COMPONENT_NAME);
    if (!config) {
        return;
    }

    const TSet<TString>& fastProperties = config->GetFastProperties();

    auto* result = context.Result.GetComponentEntity<TRTYFastArchiveParsedEntity>(FASTARCHIVE_COMPONENT_NAME);
    VERIFY_WITH_LOG(result, "fast archive entity is missing");

    TFastArchiveDocWriter& writer = result->MutableWriter();
    for (ui32 i = 0; i < context.Document.DocumentPropertiesSize(); ++i) {
        const NRTYServer::TMessage::TDocument::TProperty& property = context.Document.GetDocumentProperties(i);
        const TString& name = property.GetName();
        const TString& value = property.GetValue();
        if (!fastProperties.contains(name))
            continue;

        if (FindAnyOf(name, ";:") != TString::npos ||
            FindAnyOf(value, ";:") != TString::npos)
            throw yexception() << "fast property " << name << " has unsupported symbols (;:)";

        writer.Add(name, value);
    }
}

void TRTYFastArchiveParsedEntity::DoApplyPatch(const TParsedDocument& doc) {
    const TRTYFastArchiveParsedEntity* patch = doc.GetComponentEntity<TRTYFastArchiveParsedEntity>(FASTARCHIVE_COMPONENT_NAME);
    if (!patch)
        return;
    Writer.ApplyPatch(patch->GetWriter());
}
