#pragma once

#include "broadcast.h"

#include <saas/deploy_manager/scripts/common/scripts_helper.h>
#include <saas/deploy_manager/scripts/common/script.h>

namespace NRTYDeploy {

    class TScriptBroadcastTable : public TScriptBroadcast {
    private:

        struct TAggrData {
            TVector<TString> Data;
            ui32 CountFails;
            void AddData(const TString& data) {
                Data.push_back(data);
            }

            TString Aggregate() const {
                ui32 countNonInt = 0;
                ui64 value = 0;
                TString sumValue;
                for (ui32 i = 0; i < Data.size(); ++i) {
                    try {
                        value += FromString<ui64>(Data[i]);
                    }
                    catch (...) {
                        countNonInt++;
                    }
                    sumValue += Data[i] + " ";
                }
                if (countNonInt > Data.size() / 2) {
                    return sumValue;
                }
                else {
                    return ToString(value);
                }
            }

            TAggrData() {
                CountFails = 0;
            }
        };

        struct TReplicaInfo {
            TString ServiceName;
            TString ConfigType;
            TReplicaInfo(const TString& sN, const TString& confType) {
                ServiceName = sN;
                ConfigType = confType;
            }

            bool operator < (const TReplicaInfo& value) const {
                if (ServiceName != value.ServiceName)
                    return ServiceName < value.ServiceName;
                else
                    return ConfigType < value.ConfigType;
            }

        };

        struct TDataByFilter {
            TMap<TString, TAggrData> DBF;
            bool HasFails;
            TDataByFilter() {
                HasFails = false;
            }
        };

        typedef TMap<TBroadcastSlotData, TString> TSlotToValues;
        TMutex PrepareJsonMutex;
        TSlotToValues HtmlData;
        bool ByReplica;
        TMap<TReplicaInfo, TDataByFilter> ReplicaData;
    public:
        static TFactory::TRegistrator<TScriptBroadcastTable> Registrator;
        virtual void DoPrepareJsonForReply(const TBroadcastSlotData& slot, NJson::TJsonValue& reply) override;
        virtual bool MakeReport(IOutputStream& ss) override;
        virtual bool PrepareCustom(IDeployInfoRequest& request) override;
        virtual TString Help() override;
    };

}
