#include "task.h"
#include <saas/deploy_manager/scripts/check_slot/action/action.h>
#include <saas/deploy_manager/modules/resources/resources.h>

namespace NRTYDeploy {

    TCheckSlotsTask::TCheckSlotsTask(const TClusterTask::TCgiContext& context, NRTYDeploy::ICommonData* commonData, const TString& slotsVector)
        : TClusterTask(context, commonData, CHECK_SLOTS_TASK_TYPE)
        , SlotVectorParam(slotsVector)
    {
        SlotsVector = SplitString(slotsVector, ",");
    }

    void TCheckSlotsTask::DoBuildTask() {
        try {

            if (!SlotsVector.size()) {
                NRTYCluster::TCluster cluster = CommonData->GetResourcesManager().GetCluster(ServiceType, Service);
                if (cluster.GetCTypeCluster().contains(CType)) {
                    auto it = cluster.GetCTypeCluster().find(CType);
                    for (auto&& slot : it->second.GetSlots()) {
                        SlotsVector.push_back(slot.first);
                    }
                } else {
                    ythrow yexception() << "Incorrect CType: " << CType;
                }
            }

            for (auto&& i : SlotsVector) {
                GetScript()->AddIndependentAction(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(), CommonData->GetDeployManagerBalanserUriPrefix(),
                    new NDaemonController::TCheckSlotAction(i));
            }
        } catch (...) {
            SetStatus(ctsFailed, TClusterTask::rsFailedOnConstruction, CurrentExceptionMessage());
        }
    }

};
