#include "messages.h"
#include "reopen.h"

#include <util/system/condvar.h>
#include <util/system/mutex.h>

namespace {
    class TFakeWaitingDocument final : public TGuardedDocument {
    public:
        inline TFakeWaitingDocument(const TRTYServerConfig& config, TDuration timeout)
            : TGuardedDocument(config)
            , Timeout(timeout)
        {
        }

        void Wait() {
            with_lock(Lock) {
                if (Timeout) {
                    ProcessedInTime = CondVar.WaitT(Lock, Timeout);
                } else {
                    CondVar.Wait(Lock);
                }
            }
        }

        bool WasProcessedInTime() const {
            return ProcessedInTime;
        }

        void SetStatus(NRTYServer::TReply::TRTYStatus, const TString&) override {
            CondVar.BroadCast();
        }

    private:
        TMutex Lock;
        TCondVar CondVar;
        TDuration Timeout;
        bool ProcessedInTime = true;
    };
}

bool NRTYServer::ReopenIndexers() {
    return SendGlobalMessage<TMessageReopenIndexes>(nullptr, "").GetMessageIsProcessed();
}

bool NRTYServer::ReopenIndexersAndWait(const TRTYServerConfig& config, ui32 timeoutMs) {
    auto waitDoc = MakeAtomicShared<TFakeWaitingDocument>(config, TDuration::MilliSeconds(timeoutMs));
    auto isProcessed = SendGlobalMessage<TMessageReopenIndexes>(waitDoc, "").GetMessageIsProcessed();
    if (isProcessed) {
        waitDoc->Wait();
        isProcessed = waitDoc->WasProcessedInTime();
    }
    return isProcessed;
}
