#include "request.h"
#include "server.h"

#include <saas/rtyserver/unistat_signals/signals.h>
#include <saas/rtyserver/common/common_messages.h>
#include <saas/rtyserver/common/message_collect_server_info.h>
#include <saas/rtyserver/logging/rty_access.h>
#include <saas/rtyserver/search/source/search_replier.h>

TServerInfo TMainSearchRequest::GetServerInfo(bool isHumanReadable) const {
    TMessageCollectServerInfo info(isHumanReadable);
    return CollectServerInfo(info);
}

ISearchReplier::TPtr TMainSearchRequest::DoSelectHandler(IReplyContext::TPtr context) {
    try {
        if (BuildCommonSearch(MutableRequestData())) {
            ISearchReplier::TPtr result = CommonSearch->GetSearchReplier(RD.CgiParam.Get("meta_search"), GetFeatures().GetDefaultKps(), context);
            CHECK_WITH_LOG(!!result);
            return result;
        } else {
            return new TEmptySearchReplier(context, Metrics, Config.GetSearcherConfig());
        }
    } catch (...) {
        TSaasRTYServerSignals::DoUnistatErrorSearch();
        TRTYAccessLog::LogError(context->GetRequestId(), Now() - context->GetRequestStartTime(), CurrentExceptionMessage());
        throw;
    }
}

void TMainSearchRequest::OnBeginProcess(IReplyContext::TPtr context) {
    TRTYAccessLog::LogIncoming(
        context ? context->GetRequestId() : 0,
        IReplyContext::GetGlobalActiveObjects(),
        TString{RD.RemoteAddr()},
        TString{RD.Query()}
    );
}

TMetaSearchServerFeatures& TMainSearchRequest::GetFeatures() {
    return *Parent;
}
