#include "kpsinfo.h"

#include <saas/protos/kps_info.pb.h>

#include <library/cpp/logger/global/global.h>
#include <library/cpp/protobuf/util/pb_io.h>

bool TKpsInfo::Load(const TString& indexDir) {
    const TFsPath& path = GetFilePath(indexDir);
    if (!path.Exists()) {
        INFO_LOG << "IndexStat data " << path << " does not exist" << Endl;
        return false;
    }

    NRTYServer::TKpsInfo kpsInfo;
    if (!TryParseFromTextFormat(path, kpsInfo)) {
        ERROR_LOG << "Cannot parse " << path << Endl;
        return false;
    }

    for (size_t i = 0; i < kpsInfo.CountsSize(); i++) {
        auto& item = kpsInfo.GetCounts(i);
        Kps[item.GetKeyPrefix()] += item.GetCount();
    }

    return true;
}

void TKpsInfo::Save(const TString& indexDir) {
    NRTYServer::TKpsInfo kpsInfo;
    for (auto it = Kps.begin(); it != Kps.end(); it++) {
        if (it->second > 0) {
            NRTYServer::TKpsInfo::TItem* item = kpsInfo.MutableCounts()->Add();
            item->SetKeyPrefix(it->first);
            item->SetCount(it->second);
        }
    }

    const TFsPath& path = GetFilePath(indexDir);
    SerializeToTextFormat(kpsInfo, path);
}

NJson::TJsonValue TKpsInfo::GenerateJson() const {
    NJson::TJsonValue result(NJson::JSON_ARRAY);
    for (auto&& e : Kps) {
        const i64 kps = e.first;
        const i64 count = e.second;
        result.InsertValue(ToString(kps), count);
    }
    return result;
}

TFsPath TKpsInfo::GetFilePath(const TString& indexDir) {
    return TFsPath(indexDir) / "kpsinfo";
}
