#include "external_builder.h"
#include <library/cpp/logger/global/global.h>
#include <util/generic/singleton.h>
#include <util/system/event.h>

namespace NRTYServer {
    IExtBuilderConnection::~IExtBuilderConnection() {
    }

    class TExtBuilderEngine::TImpl {
    public:
        IExtBuilderConnection::TPtr Connection;
        TManualEvent NoWait;

    public:
        TImpl() {
            NoWait.Signal();
        }
    };

    void TExtBuilderEngine::Enable() noexcept {
        // allows waiting for connection
        Singleton<TImpl>()->NoWait.Reset();
    }

    void TExtBuilderEngine::Disable() noexcept {
        // drops connection, disallows waiting
        RegisterConnection(nullptr);
        // note: if exception is thrown from IExtBulderConnection destructor, we die
    }

    void TExtBuilderEngine::RegisterConnection(const IExtBuilderConnection::TPtr& conn) {
        Singleton<TImpl>()->Connection = conn;
        Singleton<TImpl>()->NoWait.Signal();
    }

    IExtBuilderConnection::TPtr TExtBuilderEngine::GetConnection() {
        return Singleton<TImpl>()->Connection;
    }

    IExtBuilderConnection::TPtr TExtBuilderEngine::WaitConnection(TInstant deadline) {
        TImpl& impl = *Singleton<TImpl>();

        const bool signalled = impl.NoWait.WaitD(deadline);
        if (!signalled) {
            return IExtBuilderConnection::TPtr();
        }

        return impl.Connection;
    }

}
