#include <saas/searchproxy/rearrange/clickurl/clickurl.h>

#include <search/web/core/rule.h>

#include <util/generic/algorithm.h>
#include <util/string/vector.h>
#include <util/stream/file.h>
#include <library/cpp/string_utils/url/url.h>
#include <util/string/split.h>
#include <library/cpp/string_utils/quote/quote.h>

namespace NSaas {
    class TRTYRedirectRearrangeRule: public IRearrangeRule {
        IRearrangeRuleContext* DoConstructContext() const override;
    };

    class TRTYRedirectRearrangeContext: public IRearrangeRuleContext {
    public:
        void DoRearrangeAfterFetch(TRearrangeParams& rearrangeParams) override;

    private:
        bool Disabled = false;
        bool Debug = false;
        bool ReplaceUrl = false;
        bool CountGroups = false;
        TStringBuf UrlTemplate;
    };

    IRearrangeRuleContext* TRTYRedirectRearrangeRule::DoConstructContext() const {
        return new TRTYRedirectRearrangeContext();
    }

    void TRTYRedirectRearrangeContext::DoRearrangeAfterFetch(TRearrangeParams& rearrangeParams) {
        // don't process docs of TDI-related groupings
        if (rearrangeParams.Current.Params.Attr.StartsWith("tdi_"))
            return;

        CountGroups = LocalScheme()["CountGroups"].IsTrue();
        UrlTemplate = LocalScheme()["url"].GetString();
        ReplaceUrl = LocalScheme()["ReplaceUrl"].IsTrue();
        Disabled = LocalScheme()["Disabled"].IsTrue() || LocalScheme()["RearrOff"].IsTrue();
        Debug = LocalScheme()["Debug"].IsTrue();

        if (Debug) {
            rearrangeParams.InsertWorkedRule("RedirectUrl", UrlTemplate.data());
            rearrangeParams.InsertWorkedRule("Disabled", Disabled ? "1" : "0");
        }
        if (Disabled || UrlTemplate.empty()) {
            return;
        }

        TClickUrlBuilder builder(rearrangeParams);
        builder.UrlTemplate = UrlTemplate;
        builder.ReplaceUrl = ReplaceUrl;
        builder.CountGroups = CountGroups;
        builder.ProcessMetaGrouping(rearrangeParams.Current.Grouping);
    }
}

IRearrangeRule* CreateRTYRedirectRule(const TString&, const TSearchConfig&) {
    return new NSaas::TRTYRedirectRearrangeRule();
}

REGISTER_REARRANGE_RULE(RTYRedirect, CreateRTYRedirectRule);
