#include <saas/deploy_manager/scripts/broadcast/broadcast_action.h>

#include <saas/deploy_manager/scripts/interface/dashboard_util/mapreduce_status_aggregator.h>

#include "dashboard_script.h"
#include "interface_script.h"
#include "projects_utils.h"
#include <util/string/split.h>

namespace NRTYDeploy {
    struct TDocfetcherScript : TScriptInterface {
        void DoProcess(IDeployInfoRequest& request) override {
            const auto& cgiParams = request.GetRD().CgiParam;
            NRTYDeploy::TClusterTask::TCgiContext cgi = NRTYDeploy::TClusterTask::TCgiContext::Parse(cgiParams);
            if (!cgi.Service) {
                ythrow TCodedException(400) << "Service parameter required";
            }
            THashSet<TString> slotsFilters;
            StringSplitter(request.GetRD().CgiParam.Get("slots_filters")).Split(',').AddTo(&slotsFilters);

            const TCTypeMaps sms = DoBuildSearchMap(request, cgi, slotsFilters);
            TString mapsStr;
            bool isMapMultiple;
            TDuration broadcastTimeout;
            std::tie(mapsStr, isMapMultiple, broadcastTimeout) = SerializeSearchMap(sms);

            NDaemonController::TBroadcastAction getInfoAction("get_docfetcher_status", cgi.CType, cgi.Service, cgi.ServiceType, true, mapsStr, broadcastTimeout);
            getInfoAction.SetIsMultiple(isMapMultiple);
            getInfoAction.SetWithSd(false);

            auto& filter = getInfoAction.GetFilter();
            filter.emplace("status.SearchableTimestamp");
            filter.emplace("status.Errors");

            NDaemonController::TControllerAgent agent(request.GetDeployManagerBalanserHost(), request.GetDeployManagerBalanserPort(), nullptr, request.GetDeployManagerBalanserUriPrefix());
            agent.ExecuteAction(getInfoAction);

            Report = NJson::TJsonValue{NJson::JSON_MAP};
            AggregateMapReduceStatus(getInfoAction.GetResult(), Report, cgi.Service);
            Report.InsertValue("slots", getInfoAction.GetResult());
        }
    };

    namespace {
        TDocfetcherScript::TFactory::TRegistrator<TDocfetcherScript> Registrator("docfetcher");
    }
};

