#include "total_task.h"
#include "ctype_action.h"

#include <saas/deploy_manager/modules/resources/resources.h>
#include <saas/deploy_manager/scripts/logic/action.h>
#include <saas/library/daemon_base/controller_actions/execute_script.h>
#include <library/cpp/json/json_reader.h>

using namespace NRTYDeploy;

namespace NRTYAlerts {

    TAlertsTotalTask::TAlertsTotalTask(const TClusterTask::TCgiContext& context, NRTYDeploy::ICommonData* commonData)
        : TClusterTask(context, commonData, TOTAL_ALERTS_TASK_TYPE)
    {};

    void TAlertsTotalTask::DoBuildTask() {
        try {
            TVector<TString> ctypes = CommonData->GetResourcesManager().GetCTypes();
            Sort(ctypes);
            const TString prefix = CommonData->GetConfig().GetAlertsConfig().GetCtypesPrefix();

            TVector<NRTYScript::TTaskContainer> predTasks;
            for (const auto& ctype : ctypes) {
                if (!ctype.StartsWith(prefix)) {
                    continue;
                }
                predTasks.push_back(GetScript()->AddAction(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(), CommonData->GetDeployManagerBalanserUriPrefix(),
                    new TAlertsCtypeAction(ctype, NDaemonController::apStartAndWait)));
            }
            if (!!predTasks) {
                GetScript()->AddDependentAction<NRTYScript::TSucceededChecker>(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(),
                    CommonData->GetDeployManagerBalanserUriPrefix(), new NRTYDeploy::TLogicAction(), predTasks);
            }
        } catch (...) {
            SetStatus(ctsFailed, TClusterTask::rsFailedOnConstruction, CurrentExceptionMessage());
        }
    }

};
