#include "deferred_replier.h"

TDeferredRepliesProcessor::TDeferredReplyCheck TDeferredRepliesProcessor::CheckDeferredReply(IDocumentForIndex* doc, const TString& serviceName) {
    if (!doc->GetMessageId())
        return drcNoNeed;
    if (doc->GetDeferredPolicy() != IDocumentForIndex::drpNoAsync) {
        TWriteGuard wg(Mutex);
        TString hashDoc = doc->GetDocumentHash();
        const TMaybe<TString> docUrlMaybe = doc->GetDocumentUrlMaybe();
        TReplies::iterator i = Replies.find(hashDoc);
        if (i != Replies.end()) {
            doc->SetStatus(i->second->GetStatus(), i->second->GetStatusMessage());
            if (NRTYServer::TReply::DATA_ACCEPTED != i->second->GetStatus()) {
                Replies.erase(i);
                return drcReady;
            } else
                return drcWaiting;
        } else if (doc->GetDeferredPolicy() == IDocumentForIndex::drpAsyncResponse) {
            Replies[hashDoc] = TRTYReplyWaiter(*doc);
            doc->SetStatus(Replies[hashDoc]->GetStatus(), Replies[hashDoc]->GetStatusMessage());
            doc->ExchangeReplier(new TDeferredReplier(*this, hashDoc, docUrlMaybe, serviceName, Transaction, doc->GetMessageId()));
            return drcStartNew;
        } else if (doc->GetDeferredPolicy() == IDocumentForIndex::drpEarlyResponse) {
            doc->SetStatus(NRTYServer::TReply::OK, "Document accepted for indexer");
            doc->ExchangeReplier(new TFakeReplier(Transaction, doc->GetMessageId()));
            return drcStartNew;
        }
    }
    return drcNoNeed;
}
