#pragma once

#include <saas/searchproxy/common/cgi.h>

#include <search/meta/rearrange/rearrange.h>

#include <library/cpp/string_utils/quote/quote.h>

namespace NSaas {
    class TClickUrlBuilder {
    public:
        TClickUrlBuilder(IMetaRearrangeContext::TContextParams& rearrangeParams);

        void ProcessMetaGrouping(TMetaGrouping* g);

    private:
        void ProcessDoc(ui64 docIndex, TMergedDoc& doc, TStringBuf url);

        inline bool CheckTemplate(const TStringBuf& url) {
            return !url.StartsWith(UrlTemplate);
        }

        inline TString CgiParam(const TString& name) {
            TCgiParameters::const_iterator i = Cgi.Find(name);
            if (i != Cgi.end())
                return FormParameter(name, i->second);
            return "";
        }

        inline TString CgiParam(const NSearchProxyCgi::TClickLogField& field) {
            auto i = Cgi.Find(field.CgiParam);
            if (i != Cgi.end())
                return FormParameter(field.Remap, i->second, field.Escape);
            return "";
        }

        inline TString FormParameter(const TString& name, const TString& value, bool escape = true) {
            return "/" + name + "=" + (escape ? CGIEscapeRet(value) : value);
        }
    private:
        IMetaRearrangeContext::TContextParams& RearrangeParams;
        const TCgiParameters& Cgi;

        TString Service;
        TString MetaService;
        TString UserRequest;
    public:
        TString UrlTemplate;
        bool ReplaceUrl;
        bool CountGroups;
    };
}
