#include "statistics.h"

namespace NPrivate {


    TStatisticsField::TStatisticsField(const TString& valuePath, const TString& caption)
        : Caption(caption)
    {
        ValuePath.insert(valuePath);
    }


    ui64 TStatisticsFieldOneParam::GetValue() const {
        return Value;
    }

    void TStatisticsFieldOneParam::UpdateValue(const NJson::TJsonValue& value) {
        for (const auto& vp : ValuePath) {
            const NJson::TJsonValue* v = value.GetValueByPath(vp, '.');
            if (v)
                DoUpdateValue(v->GetUIntegerRobust());
        }
    }

    TStatisticsFieldOneParam::TStatisticsFieldOneParam(const TString& valuePath, const TString& caption)
        : TStatisticsField(valuePath, caption)
        , Value(0)
    {}


    void TStatisticsFieldSum::DoUpdateValue(ui64 value) {
        Value += value;
    }

    TStatisticsFieldSum::TStatisticsFieldSum(const TString& valuePath, const TString& caption)
        : TStatisticsFieldOneParam(valuePath, caption)
    {}


    ui64 TStatisticsFieldGroupedSet::GetValue() const {
        ui64 result = 0;
        for (const auto& v : Values)
            result += AverageValue(v.second);
        return result;
    }

    void TStatisticsFieldGroupedSet::UpdateValue(const NJson::TJsonValue& value) {
        const NJson::TJsonValue* g = value.GetValueByPath(GroupBy, '.');
        TString group;
        if (g)
            group = g->GetStringRobust();
        ui64 sum = 0;
        for (const auto& vp : ValuePath)
            if (const NJson::TJsonValue* v = value.GetValueByPath(vp, '.'))
                sum += v->GetUIntegerRobust();
        Values[group][sum]++;
    }

    TStatisticsFieldGroupedSet::TStatisticsFieldGroupedSet(const TString& valuePath, const TString& caption, const TString& groupBy)
        : TStatisticsField(valuePath, caption)
        , GroupBy(groupBy)
    {}
}
