#include "parsed_entity.h"
#include "config.h"
#include "const.h"

#include <library/cpp/logger/global/global.h>

TTrigramParsedEntity::TTrigramParsedEntity(TConstructParams& params)
    : TParsedDocument::TParsedEntity(params)
{
}

TTrigramComponentParser::TTrigramComponentParser(const TRTYServerConfig& config)
{
    Config = config.ComponentsConfig.Get<TTrigramComponentConfig>(NRTYServer::TrigramComponentName);
}

void TTrigramComponentParser::Parse(TParsingContext& context) const {
    auto entity = context.Result.GetComponentEntity<TTrigramParsedEntity>(NRTYServer::TrigramComponentName);
    CHECK_WITH_LOG(entity);
    for (ui32 i = 0; i < context.Document.TrigramIndexedPropsSize(); ++i) {
        const auto prop = context.Document.GetTrigramIndexedProps(i);
        if (!prop.GetName()) {
            ythrow yexception() << "Incorrect name for special key: empty" << Endl;
        }
        if (!prop.GetValue()) {
            ythrow yexception() << "Incorrect special key value for " << prop.GetName() << ": key's value is empty" << Endl;
        }

        TString trigram;
        TString text = prop.GetValue();
        TString name = prop.GetName();
        for (size_t i = 0; i < text.size() - 2; i++) {
            trigram = text.substr(i, 3);
            TDocSearchInfo dsi(trigram, context.Document.GetKeyPrefix());
            entity->AddData(name, dsi, 0);
            if (Config->IsIgnoreCase()) {
                TDocSearchInfo dsi(to_lower(trigram), context.Document.GetKeyPrefix());
                entity->AddData(TString::Join(name, '@'), dsi, 0);
            }
        }
    }
}
