#include "script.h"
#include <saas/deploy_manager/server/client/client.h>
#include <saas/util/external/diff.h>
#include <library/cpp/logger/global/global.h>
#include <util/folder/pathsplit.h>
#include <util/folder/path.h>
#include <util/string/hex.h>

namespace NRTYDeploy {
    void TScriptSetConf::FillUsedResources(IUserAccessControl::TUsedResources& result, IDeployInfoRequest& request) {
        const TString service = request.GetRD().CgiParam.Get("service");
        const TString filename = request.GetRD().CgiParam.Get("filename");
        TString root = "configs";
        if (request.GetRD().CgiParam.Has("root"))
            root = request.GetRD().CgiParam.Get("root");
        TString path = root + "/" + service + "/" + filename;
        const TPathSplit& split = TFsPath(path).Fix().PathSplit();
        if (split.size() >= 2 && split[0] == "configs")
            result.Services.insert(split[1].data());
        else
            result.Services.insert("all_services");

    }

    bool TScriptSetConf::Process(IDeployInfoRequest& request) {
        const TString service = request.GetRD().CgiParam.Get("service");
        const TString filename = request.GetRD().CgiParam.Get("filename");

        TBlob fileData = request.GetBlob();

        DEBUG_LOG << "POST data size = " << fileData.Length() << Endl;

        TString root = "configs";
        if (request.GetRD().CgiParam.Has("root"))
            root = request.GetRD().CgiParam.Get("root");

        if (!filename) {
            request.Output() << "HTTP/1.1 400 \r\n";
            request.Output() << "Empty filename";
            return false;
        }

        TString oldData;
        TString blobData(fileData.AsCharPtr(), fileData.Length());
        TString newData;
        if (request.GetRD().CgiParam.Get("hex") == "yes") {
            newData = HexDecode(blobData);
        }
        else {
            newData = blobData;
        }

        i64 version;
        request.GetStorage().GetValue(root + "/" + service + "/" + filename, oldData);
        if (!request.GetStorage().SetValue(root + "/" + service + "/" + filename, newData, true, true, &version)) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Incorrect resource " << root << "/" + service + "/" + filename;
            return false;
        } else {
            NJson::TJsonValue reply;
            reply.InsertValue("content_hash", MD5::Calc(newData));
            reply.InsertValue("version", version);
            request.Output() << "HTTP/1.1 200 \r\n\r\n"
                << reply.GetStringRobust();

            SetData(oldData, newData);
            SetAdditionalMessage("PATH:\n/" + service + "/" + filename);
        }
        return true;
    };

    IScript::TFactory::TRegistrator<TScriptSetConf> TScriptSetConf::Registrator("set_conf");
}
