#include "dispatch_queue.h"
#include "dispatcher.h"

#include <saas/library/behaviour/behaviour.h>
#include <saas/library/indexer_protocol/protocol.h>
#include <saas/indexerproxy/server/request_opts.h>

#include <yweb/realtime/distributor/client/distclient.h>

using namespace NSearchMapParser;
using namespace NRealTime;

TDispatchServiceSelector::TDispatchServiceSelector(TDispatcher& dispatcher)
    : Dispatcher(dispatcher)
    , Config(dispatcher.GetConfig())
    , Distributors(Config)
    , Requester(Config.GetOwner().GetServicesConfig().GetDefaultConfig().SendAttemptsCount, NNeh::ProtocolFactory()->Protocol(NRTYServer::IndexingNehProtocol))
{
    PersQueueManager.Init(Config.GetOwner());

    RegisterGlobalMessageProcessor(this);
    Requester.Start(Config.GetSenderThreads());
}

TDispatchServiceSelector::~TDispatchServiceSelector() {
    UnregisterGlobalMessageProcessor(this);
}

bool TDispatchServiceSelector::Process(IMessage* message) {
    TMessageCollectIndexerProxyInfo* messageInfo = dynamic_cast<TMessageCollectIndexerProxyInfo*>(message);
    if (messageInfo) {
        TGuard<TMutex> g(Mutex);
        messageInfo->GetTasks()["common"] = Requester.QueueSize();
        return true;
    }
    return false;
}
