#include "clickurl.h"

#include <search/meta/mergedres.h>


void NSaas::TClickUrlBuilder::ProcessDoc(ui64 docIndex, TMergedDoc& doc, TStringBuf url)
{
    if (MetaService && Service != MetaService)
        return;

    TMergedDoc::TDocAttributes* docAttrs = doc.MutableAttributes();
    if (!docAttrs)
        return;

    if (!CheckTemplate(doc.Url()) || docAttrs->Has("clickUrl"))
        return;

    TString urlEncode(url);
    Quote(urlEncode, "");

    TStringStream ss;
    ss << "SAAS" << FormParameter("p", ToString(docIndex))
        << FormParameter("saas_url", urlEncode, false)
        << FormParameter("robot", ToString(IsTrue(Cgi.Get(NSearchProxyCgi::robot))))
        << FormParameter("r", UserRequest);

    for (size_t i = 0; i < Y_ARRAY_SIZE(NSearchProxyCgi::ClickLogging); ++i)
        ss << CgiParam(NSearchProxyCgi::ClickLogging[i]);

    // tdi support
    const TStringBuf tdiMarker = RearrangeParams.GetDocMarker(doc, "TdiSrc");
    if (!!tdiMarker)
        ss << FormParameter("source", TString(tdiMarker));

    ss << "/*data=url%3D" << urlEncode;

    docAttrs->Add("clickUrl", ss.Str());

    if (ReplaceUrl) {
        docAttrs->Add("_OriginalUrl", doc.Url());
        doc.SetUrl(UrlTemplate + "/redir/dtype=" + ss.Str());
    }
}

void NSaas::TClickUrlBuilder::ProcessMetaGrouping(TMetaGrouping* g)
{
    ui32 docIndexGlobal = 0;
    for (size_t ind = 0; ind < g->Size(); ind++) {
        TMetaGroup::TDocs& docs = g->GetMetaGroup(ind).MetaDocs;
        TStringBuf groupUrl;
        for (size_t docInd = 0; docInd < docs.size(); docInd++) {
            if (!groupUrl) {
                groupUrl = docs[0].Url();
            }

            TMergedDoc& doc = docs[docInd];
            ProcessDoc(docIndexGlobal, doc, CountGroups ? groupUrl : TStringBuf(doc.Url()));
            if (!CountGroups) {
                ++docIndexGlobal;
            }
        }

        if (CountGroups) {
            ++docIndexGlobal;
        }
    }
}

NSaas::TClickUrlBuilder::TClickUrlBuilder(IMetaRearrangeContext::TContextParams& rearrangeParams)
    : RearrangeParams(rearrangeParams)
    , Cgi(rearrangeParams.GetRequestCgi())
    , ReplaceUrl(false)
    , CountGroups(false)
{
    Service = Cgi.Get(NSearchProxyCgi::service);
    MetaService = Cgi.Get(NSearchProxyCgi::metaservice);
    UserRequest = Cgi.Get("user_request");
    if (!UserRequest) {
        UserRequest = Cgi.Get("text");
    }
    Quote(UserRequest, "");
}
