#include "script.h"
#include "task.h"

#include <saas/deploy_manager/scripts/common/scripts_helper.h>
#include <saas/deploy_manager/server/client/client.h>

#include <saas/library/searchmap/searchmap.h>

#include <util/string/type.h>

namespace NRTYDeploy {

    TClusterTask::TPtr TScriptIndexRestore::DoBuildTask(IDeployInfoRequest& request) const {
        const TCgiParameters& cgi = request.GetRD().CgiParam;
        const TString& notUsefulSlots = cgi.Get("not_useful_slots");
        const TString& restoreSlots = cgi.Get("restore_slots");
        const TClusterTask::TCgiContext context = TClusterTask::TCgiContext::Parse(cgi);

        DEBUG_LOG << "Restore task.restore_slots = " << restoreSlots << Endl;
        DEBUG_LOG << "Restore task.not_useful_slots = " << notUsefulSlots << Endl;

        if (!context.Service) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "service does not set";
            return nullptr;
        }

        if (!context.CType) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "ctype does not set";
            return nullptr;
        }

        NSearchMapParser::TSlotsPool restoreHosts;
        if (!restoreSlots || !restoreHosts.DeserializeFromString(restoreSlots) || !restoreHosts.GetSlots().size()) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "incorrect restore_slots description: " << restoreSlots;
            return nullptr;
        }

        const TVector<TString> notUsefulHosts = SplitString(notUsefulSlots, ",");

        return new TRestoreIndexTask(restoreHosts, notUsefulHosts, context, &request);
    }

    IScript::TFactory::TRegistrator<TScriptIndexRestore> TScriptIndexRestore::Registrator("restore_index");
}
