#include "text.h"
#include "hasher.h"

#include <balancer/kernel/http/parser/http.h>
#include <balancer/kernel/memory/split.h>
#include <balancer/kernel/module/iface.h>

#include <util/random/random.h>

using namespace NSrvKernel;
using namespace NModHasher;

HASHER(text) {
    THasher(const TModuleParams&) {}

    TErrorOr<ui64> CalcHash(const TConnDescr& descr) const noexcept override {
        auto str = ToString(descr.Request->RequestLine().CGI);

        size_t pos = str.find("&text=");
        if (pos == TString::npos) {
            pos = str.find("?text=");
            if (pos == TString::npos) {
                return RandomNumber<ui64>();
            }
        }
        size_t endPos = str.find('&', pos + 1);
        if (endPos == TString::npos) {
            endPos = str.size();
        }

        TStringBuf strBuf = TStringBuf{str}.substr(pos + 1, endPos - pos - 1);

        TMurmurHash2A<size_t> hash;
        hash.Update(strBuf.data(), strBuf.size());
        return hash.Value();
    }
};

INodeHandle<IHasher>* NModHasher::NText::Handle() {
    return THasher::Handle();
}
