#include "task.h"
#include <saas/deploy_manager/meta/cluster.h>
#include <saas/deploy_manager/scripts/searchmap/action.h>
#include <saas/deploy_manager/scripts/deploy/action.h>
#include <saas/rtyserver/controller/controller_actions/clear_index_action.h>
#include <saas/deploy_manager/scripts/common/deploy/deploy_builder.h>

namespace NRTYDeploy {

    TReleaseTask::TReleaseTask(const TVector<TString>& slots, const TClusterTask::TCgiContext& context, NRTYDeploy::ICommonData* commonData, bool deploy, bool deployProxies)
        : TClusterTask(context, commonData, RELEASE_TASK_TYPE)
        , Deploy(deploy)
        , DeployProxies(deployProxies)
    {
        Slots.Parse(slots);
    }

    void TReleaseTask::DoBuildTask() {

        NRTYDeployInfo::IDeployComponentInfo::TPtr info = NRTYDeployInfo::IDeployComponentInfo::TFactory::Construct(ServiceType);
        if (!info) {
            SetStatus(ctsFailed, TClusterTask::rsFailedOnConstruction, "Incorrect service type: " + ServiceType);
            return;
        }
        info->SetInfo(CommonData, CType);
        auto ism = info->SearchMap(Service);

        const NSearchMapParser::TSearchMapService* service = ism.GetService(Service);
        if (!service) {
            SetStatus(ctsFailed, TClusterTask::rsFailedOnConstruction, "Can't read service " + Service + " info");
            return;
        }

        const TVector<NSearchMapParser::TSearchMapHost>& slots = Slots.GetSlots();
        if (slots.empty()) {
            SetStatus(ctsFailed, TClusterTask::rsFailedOnConstruction, "no slots");
            return;
        }

        NDaemonController::TAction::TPtr actionRelease = new NDaemonController::TSimpleSearchmapModifAction(Slots, CType, Service, "release", ServiceType, Deploy, DeployProxies);
        GetScript()->AddAction(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(), CommonData->GetDeployManagerBalanserUriPrefix(), actionRelease);

        TVector<TString> taskNames;
        for (ui32 i = 0; i < slots.size(); ++i) {
            NDaemonController::TAction::TPtr action = new NDaemonController::TClearIndexAction(NDaemonController::apStart);
            taskNames.push_back(GetScript()->AddAction(slots[i].Name, slots[i].ControllerPort(), "", action, true).GetName());
        }
        for (ui32 i = 0; i < slots.size(); ++i) {
            NDaemonController::TAction::TPtr action = new NDaemonController::TClearIndexAction(taskNames[i]);
            GetScript()->AddAction(slots[i].Name, slots[i].ControllerPort(), "", action);
        }


        NDaemonController::TAction::TPtr actionDeploy = new NRTYDeploy::TDeployAction(UNUSED_SERVICE, CType, "CURRENT", NDaemonController::apStartAndWait, ServiceType, 1, &Slots);
        GetScript()->AddAction(CommonData->GetDeployManagerBalanserHost(), CommonData->GetDeployManagerBalanserPort(), CommonData->GetDeployManagerBalanserUriPrefix(), actionDeploy);
    }

};
