#ifndef INCLUDED_BOBCAT_SEMAPHORE_
#define INCLUDED_BOBCAT_SEMAPHORE_

#include <mutex>
#include <condition_variable>
#include <chrono>

namespace FBB
{

class Semaphore
{
    std::mutex d_mutex;
    std::condition_variable d_condition;
    size_t d_nAvailable;

    public:
        Semaphore(size_t nAvailable);

        template <typename Fun, typename ...Params>
        bool wait(Fun fun, Params &&...args);        // wait # available

        void wait();        // wait # available

                            // wait for duration timeunits
        template <typename Rep, typename Period>
        std::cv_status wait_for(std::chrono::duration<Rep, Period>
                                                            const &relTime);

                            // wait until abs. time has been reached
        template <typename Clock, typename Duration>
        std::cv_status wait_until(std::chrono::time_point<Clock, Duration>
                                                            const &absTime);

        void notify();      // notify a single waiting thread if initially 0
        void notify_all();  // notify_all # available, notify if initially 0

        void set(size_t available = 0);
        size_t size() const;
};

inline size_t  Semaphore::size() const
{
    return d_nAvailable;
}
template <typename Rep, typename Period>
std::cv_status Semaphore::wait_for(
                        std::chrono::duration<Rep, Period> const &relTime)
{
    std::unique_lock<std::mutex> lk(d_mutex);   // get the lock
    while (d_nAvailable == 0)
        if (d_condition.wait_for(lk, relTime) == std::cv_status::timeout)
            return std::cv_status::timeout;

    --d_nAvailable;
    return std::cv_status::no_timeout;
}
template <typename Clock, typename Duration>  // wait until abs. time
std::cv_status Semaphore::wait_until(std::chrono::time_point<Clock, Duration>
                                     const &absTime)
{
    std::unique_lock<std::mutex> lk(d_mutex);   // get the lock
    while (d_nAvailable == 0)
        if (d_condition.wait_until(lk, absTime) == std::cv_status::timeout)
            return std::cv_status::timeout;

    --d_nAvailable;
    return std::cv_status::no_timeout;
}
template <typename Fun, typename ...Params>
bool Semaphore::wait(Fun fun, Params &&...args)
{
    std::unique_lock<std::mutex> lk(d_mutex);   // get the lock
    while (d_nAvailable == 0)
    {
        d_condition.wait(lk);   // see 'wait.cc'
                                                    // called on notifications
        if (not fun(std::forward<Params>(args)...))
            return false;
    }
    --d_nAvailable;              // dec. semaphore
    return true;
}


}   // FBB

#endif
