#include "search.h"
#include "context.h"

#include <saas/library/daemon_base/metrics/servicemetrics.h>
#include <saas/searchproxy/rank/rank.h>
#include <saas/searchproxy/experiment/context.h>
#include <saas/searchproxy/experiment/ctx_creator.h>

#include <search/session/noapache.h>

namespace {
    class TMetaSearchContextHolder: public THolder<ISearchContext, TNoAction> {
    private:
        using TBase = THolder<ISearchContext, TNoAction>;

    public:
        TMetaSearchContextHolder(const TMetaSearch* search, ISearchContext* context)
            : TBase(context)
            , Search(search)
        {
            CHECK_WITH_LOG(Search);
        }
        ~TMetaSearchContextHolder() {
            if (auto context = Release()) {
                Search->DestroyContext(context);
            }
        }

    private:
        const TMetaSearch* Search;
    };

}

NSearchProxy::TCommonMetaSearch::TCommonMetaSearch(const TServiceConfig& serviceConfig, const TSourcesConfig& searchConfig
        , ICgiCorrectorPtr cgiCorrector, TServiceMetricPtr metric, TEventLogPtr eventlog)
    : TRaiiSearch(serviceConfig, searchConfig, this, eventlog)
{
    CgiCorrector = cgiCorrector;
    Metric = metric;
}

ISearchContext* NSearchProxy::TCommonMetaSearch::CreateContext() const {
    return new TCgiAwareSearchContext(*this, TemplateCorrector, MisspellCorrector, CgiCorrector, ServiceConfig);
}

ISearchContext* NSearchProxy::TCommonMetaSearch::CreateContext(const TSearchRequestData& /*rd*/) const {
    return CreateContext();
}

TAutoPtr<IMetaRankEnv> NSearchProxy::TCommonMetaSearch::CreateMetaRankEnv(const TSearchConfig& /*config*/) const {
    return NRTYSearchProxy::CreateMetaRankEnv(ServiceConfig);
}
