#include "erf_manager.h"
#include "erf_parsed_entity.h"
#include <saas/rtyserver/common/common_rty.h>
IRTYErfManager::IRTYErfManager(const TString& componentName)
    : NRTYServer::IIndexComponentManager(componentName)
{
}

bool IRTYErfManager::UpdateDoc(ui32 docId, const TParsedDocument::TPtr doc) {
    const TRTYErfParsedEntity* patch = doc->GetComponentEntity<TRTYErfParsedEntity>(ComponentName);
    if (!patch || patch->GetValues().Size() == 0)
        return false;
    TBasicFactorStorage data(GetFactorsInfo()->GetStaticFactorsCount());
    ReadRaw(data, docId);
    patch->Apply(data);
    Write(data, docId);
    return true;
}

bool IRTYErfReader::GetErfDocInfo(const IRTYStaticFactors* factors, const ui32 docId, NJson::TJsonValue& result) const {
    if (docId >= Size() || !factors)
        return false;

    const ui32 factorsCount = factors->GetStaticFactorsCount();
    TBasicFactorStorage factorValues(factorsCount);
    factorValues.Clear();
    if (!ReadRaw(factorValues, docId)) {
        ERROR_LOG << "Cannot read static factors values for docId " << docId << Endl;
        return false;
    }

    for (ui32 i = 0; i < factorsCount; ++i) {
        const auto& factor = factors->GetFactor(i);
        const bool isInteger = factor.Type == TBitsReader::ftInt;
        if (isInteger)
            result.InsertValue(factor.Name, (ui32&)factorValues[i]);
        else
            result.InsertValue(factor.Name, factorValues[i]);
    }
    return true;
}

bool IRTYErfManager::GetDocInfo(const ui32 docId, NJson::TJsonValue& result) const {
    return GetErfDocInfo(GetFactorsInfo(), docId, result);
}
