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

namespace NRTYDeploy {
    bool TScriptGetConf::Process(IDeployInfoRequest& request) {
        TFileContentGenerator::TContext context;
        context.SlotInfo.Service = request.GetRD().CgiParam.Get("service");
        context.SlotInfo.ServiceType = request.GetRD().CgiParam.Get("service_type");
        if (!context.SlotInfo.ServiceType)
            context.SlotInfo.ServiceType = RTYSERVER_SERVICE;
        context.SlotInfo.CType = request.GetRD().CgiParam.Get("ctype");
        context.SlotInfo.Slot = request.GetRD().CgiParam.Get("slot");
        const TString& filename = request.GetRD().CgiParam.Get("filename");
        const TString& version = request.GetRD().CgiParam.Get("version");
        TString root = "configs";
        if (request.GetRD().CgiParam.Has("root"))
            root = request.GetRD().CgiParam.Get("root");

        const i64 ver = !!version ? FromString(version) : -1;

        TFileContentGenerator::TPtr gen(TFileContentGenerator::Deserialize(request, context, root, filename, ver));
        context.NoAnyPatch = request.GetRD().CgiParam.Get("orig") == "da";
        TString content;
        if (!gen->GetContent(content, request, context)) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Incorrect resource " << "/" << root << "/" + context.SlotInfo.Service + "/" + filename;
            return false;
        } else {
            request.Output() << "HTTP/1.1 200 \r\n\r\n";
            request.Output() << content;
        }
        return true;
    };

    IScript::TFactory::TRegistrator<TScriptGetConf> TScriptGetConf::Registrator("get_conf");
}
