#include "script.h"
#include <saas/deploy_manager/server/client/client.h>
#include <saas/deploy_manager/scripts/check_slots/task/task.h>
#include <saas/deploy_manager/scripts/cluster_control/task/task.h>
#include <saas/deploy_manager/scripts/common/scripts_helper.h>

#include <util/string/type.h>

namespace NRTYDeploy {

    inline TVector<TString> ParseCgiCSV(const TCgiParameters& cgi, const TString& paramName) {
        TVector<TString> res;
        if (cgi.Has(paramName)) {
            res = SplitString(cgi.Get(paramName), ",");
        }
        return res;
    }

    TClusterTask::TPtr TScriptClusterControl::DoBuildTask(IDeployInfoRequest& request) const {
        const TCgiParameters& cgi = request.GetRD().CgiParam;
        const TClusterTask::TCgiContext context = TClusterTask::TCgiContext::Parse(cgi);
        if (!context.CType) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "ctype does not set";
            return nullptr;
        }

        const TVector<TString> predefRestore = ParseCgiCSV(cgi, "restore_slots");
        const TVector<TString> newSlotsPool = ParseCgiCSV(cgi, "new_slots_pool");
        const TVector<TString> copySlotsPool = ParseCgiCSV(cgi, "copy_slots");
        const TVector<TString> predefReplace = ParseCgiCSV(cgi, "replace_slots");
        const TVector<TString> predefAbsentReplace = ParseCgiCSV(cgi, "absent_replace_slots");

        const bool deployProxies = !cgi.Has("deploy_proxies") || IsTrue(cgi.Get("deploy_proxies"));
        const float mayBeDeadIntervalPercentage = cgi.Has("may_be_dead_procentage") ? FromString<float>(cgi.Get("may_be_dead_procentage")) : 0.5f;

        return new TClusterControlTask(context, &request, predefRestore, predefReplace, copySlotsPool, newSlotsPool, predefAbsentReplace,
            deployProxies, mayBeDeadIntervalPercentage);
    }

    IScript::TFactory::TRegistrator<TScriptClusterControl> TScriptClusterControl::Registrator("cluster_control");
}
