#include "task.h"
#include "action.h"
#include "set_slot_info_action.h"

#include <saas/deploy_manager/scripts/deploy/action.h>
#include <saas/deploy_manager/scripts/logic/action.h>

namespace NRTYDeploy {

    TModifySearchmapTask::TModifySearchmapTask(const NSearchMapParser::TSlotsPool& slots, const TString& action,
        const TClusterTask::TCgiContext& context, NRTYDeploy::ICommonData* commonData, bool deployProxies, float mayBeDeadIntervalPercentage)
        : TClusterTask(context, commonData, "MODIFY_SEARCHMAP_TASK")
    {
        Slots = slots;
        Action = action;
        MayBeDeadIntervalPercentage = mayBeDeadIntervalPercentage;
        DeployProxies = deployProxies;
    }


    void TModifySearchmapTask::ReplaceInterval(const TString& from, const TString& to) {
        NSearchMapParser::TShardsInterval fI, toI;
        if (!NSearchMapParser::TShardsInterval::Parse(from, fI) || !NSearchMapParser::TShardsInterval::Parse(to, toI))
            ythrow yexception() << "invalid interval: " << from << "->" << to;
        ReplaceIntervals[fI] = toI;
    }

    void TModifySearchmapTask::DoBuildTask() {
        THolder<NDaemonController::TSimpleSearchmapModifAction> sm = MakeHolder<NDaemonController::TSimpleSearchmapModifAction>(Slots, CType, Service, Action, ServiceType);
        for (const auto& interval : ReplaceIntervals) {
            sm->ReplaceInterval(interval.first, interval.second);
        }
        NRTYScript::TSlotTaskContainer startTask = GetScript()->AddAction(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(), CommonData->GetDeployManagerBalanserUriPrefix(), sm.Release());

        if (DeployProxies) {
            startTask.AddNext(*GetScript(), new NRTYDeploy::TDeployAction(Service, CType,
                "NEW", NDaemonController::apStartAndWait, INT_SERVICE, MayBeDeadIntervalPercentage));
            startTask.AddNext(*GetScript(), new NRTYDeploy::TDeployAction(SEARCH_PROXY_SERVICE, CType,
                "NEW", NDaemonController::apStartAndWait, SEARCH_PROXY_SERVICE, MayBeDeadIntervalPercentage));
            startTask.AddNext(*GetScript(), new NRTYDeploy::TDeployAction(INDEXER_PROXY_SERVICE, CType,
                "NEW", NDaemonController::apStartAndWait, INDEXER_PROXY_SERVICE, MayBeDeadIntervalPercentage));
        }

        if (Action != "release") {
            TString modActionName = startTask.GetName();
            const TVector<NSearchMapParser::TSearchMapHost>& slots = Slots.GetSlots();
            for (TVector<NSearchMapParser::TSearchMapHost>::const_iterator i = slots.begin(); i != slots.end(); ++i) {
                NDaemonController::TAction::TPtr action = new NDaemonController::TSetSlotInfoAction(modActionName + "-action.task.result_searchmap", i->GetDescription(), Service, ServiceType, CType);
                GetScript()->AddDependentAction(i->Name, i->ControllerPort(), "", action, startTask);
            }
        }
    }

};
