#include "hits_builder.h"
#include <library/cpp/json/writer/json_value.h>

void THitsBuilderDetail::SerializeHitsInfo(ui32 docId, TArrayRef<const char * const> attrNames, IAttributeWriter& write) {
    constexpr TStringBuf hitsInfo{"__HitsInfo"};
    if (std::find(attrNames.begin(), attrNames.end(), hitsInfo) == attrNames.end()) {
        return;
    }
    auto it = Hits.find(docId);
    if (Hits.end() != it) {
        NJson::TJsonValue jsonHits;
        for (auto&& i : it->second) {
            NJson::TJsonValue posInfo;
            posInfo.InsertValue("sent", TWordPosition::Break(i.Pos.Beg));
            posInfo.InsertValue("word", TWordPosition::Word(i.Pos.Beg));
            jsonHits.AppendValue(posInfo);
        }
        write(hitsInfo, jsonHits.GetStringRobust());
        Hits.erase(it);
    }
}

void THitsBuilderDetail::SerializeQueryHitsInfo(ui32 docId, TArrayRef<const char * const> attrNames, IAttributeWriter& write) {
    constexpr TStringBuf queryHitsInfo{"__QueryHitsInfo"};
    if (std::find(attrNames.begin(), attrNames.end(), queryHitsInfo) == attrNames.end()) {
        return;
    }
    auto it = TextHits.find(docId);
    NJson::TJsonValue jsonHits;
    if (TextHits.end() != it) {
        jsonHits = it->second.SerializeAsJson(HitInfos);
        TextHits.erase(it); // why?
    }
    it = AnnHits.find(docId);
    if (AnnHits.end() != it) {
        jsonHits.InsertValue("ann_hits", it->second.SerializeAsJson(Nothing()));
        AnnHits.erase(it);
    }
    write(queryHitsInfo, jsonHits.GetStringRobust());
}

void THitsBuilderDetail::SerializeFirstStageAttributes(ui32 docId, TArrayRef<const char * const> attrNames, IAttributeWriter& write) {
    SerializeHitsInfo(docId, attrNames, write);
    SerializeQueryHitsInfo(docId, attrNames, write);
}

