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

#include <saas/deploy_manager/server/client/client.h>

#include <util/string/type.h>

namespace NRTYDeploy {

    void TScriptDeploy::FillUsedResources(IUserAccessControl::TUsedResources& result, IDeployInfoRequest& request) {
        if (request.GetRD().CgiParam.Has("service"))
            result.Services.insert(request.GetRD().CgiParam.Get("service"));
    }

    TClusterTask::TPtr TScriptDeploy::DoBuildTask(IDeployInfoRequest& request) const {
        const TCgiParameters& cgi = request.GetRD().CgiParam;
        TClusterTask::TCgiContext context = TClusterTask::TCgiContext::Parse(cgi);
        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;
        }
        if (TDeployBlockMaker(context.Service, context.CType, request).IsBlocked()) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "deploy for service is blocked, see deploy_block.conf for details";
            return nullptr;
        }

        TString version = cgi.Get("version");
        float mayBeDeadInIntervalPercentage = 0.01f;
        if (cgi.Has("may_be_dead_procentage"))
            mayBeDeadInIntervalPercentage = FromString<float>(cgi.Get("may_be_dead_procentage"));
        TAtomicSharedPtr<NSearchMapParser::TSlotsPool> slotsFilter;
        if (cgi.Has("slots")) {
            slotsFilter.Reset(new NSearchMapParser::TSlotsPool);
            if (!slotsFilter->DeserializeFromString(cgi.Get("slots"))) {
                request.Output() << "HTTP/1.1 400 \r\n\r\n";
                request.Output() << "invalid slotsFilter set";
                return nullptr;
            }
        }
        return new TDeployTask(context, version, &request, mayBeDeadInIntervalPercentage,
            slotsFilter, cgi.Get("force_services"), IsTrue(cgi.Get("diff_slots_only")));
    }

    IScript::TFactory::TRegistrator<TScriptDeploy> TScriptDeploy::Registrator("deploy");
}
