#include <saas/deploy_manager/modules/services20/module.h>
#include <saas/deploy_manager/server/client/client.h>
#include <saas/deploy_manager/scripts/common/script.h>

namespace NRTYDeploy {
    class TScriptServices20AllocateSlots : public IScript {
    public:
        static TFactory::TRegistrator<TScriptServices20AllocateSlots> Registrator;

        bool Process(IDeployInfoRequest& request) override {
            const TCgiParameters& cgi = request.GetRD().CgiParam;
            const TString& ctype = cgi.Get("ctype");
            const TString& service = cgi.Get("service") + "_" + ctype;
            TString result;
            try {
                request.GetServices20Module().CreateSevice(service);
            } catch (...) {
                result += "On create service: " + CurrentExceptionMessage() + "\n";
            }
            try {
                request.GetServices20Module().SetServiceAttrs(service);
            } catch (...) {
                result += "On set service attrs: " + CurrentExceptionMessage() + "\n";
            }
            try {
                TServices20Module::TAllocatedSlot slot = request.GetServices20Module().CreateOneSlotAllocation(cgi.Get("location"), service, ctype);
                result += "id=" + slot.Id + ";";
                result += "host=" + slot.Host + ";";
                result += "ports=" + ToString(slot.SearchPort) + "," + ToString(slot.BaseSearchPort) + "," + ToString(slot.IndexPort) + "," + ToString(slot.ControllerPort) + ";\n";
            } catch (...) {
                result += "On allocate slot: " + CurrentExceptionMessage() + "\n";
            }
            ythrow yexception() << result;
            return true;
        }
    };

    static TScriptServices20AllocateSlots::TFactory::TRegistrator<TScriptServices20AllocateSlots> Registrator("service20_allocate");
};

